Dates: Date Recipes

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Getting the current timestamp

The UNIX timestamp is an integer that represents the number of seconds elapsed since January 1 1970.

On UNIX-like machines, which include Linux and macOS, you can type date +%s in the terminal and get the UNIX timestamp back:

$ date +%s
1524379940

The current timestamp can be fetched by calling the now() method on the Date object:

Date.now()

You could get the same value by calling

new Date().getTime()

or

new Date().valueOf()

The timestamp in JavaScript is expressed in milliseconds.

To get the timestamp expressed in seconds, convert it using:

Math.floor(Date.now() / 1000)

Note: some tutorials use Math.round(), but that will approximate to the next second even if the second is not fully completed.

Or, less readable:

~~(Date.now() / 1000)

You might also see:

+new Date

which might seem a weird statement, but it’s perfectly correct JavaScript code. The unary operator + automatically calls the valueOf() method on any object it is assigned to, which returns the timestamp (in milliseconds). The problem with this code is that you instantiate a new Date object that’s immediately discarded.

To generate a date from a timestamp, use new Date(<timestamp>) but make sure you pass a number (a string will get you an “invalid date” result - use parseInt() in doubt).

Sorting an array by date

Say you have an array of objects like this, which contains a set of date objects:

const activities = [
  { title: 'Hiking', date: new Date('2019-06-28') },
  { title: 'Shopping', date: new Date('2019-06-10') },
  { title: 'Trekking', date: new Date('2019-06-22') }
]

You want to sort those activities by the date property.

You can use the sort() method of Array, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b):

const sortedActivities = activities.sort((a, b) => b.date - a.date)

When we return a positive value, the function communicates to sort() that the object b takes precedence in sorting over the object a. Returning a negative value will do the opposite.

The sort() method returns a new sorted array, but it also sorts the original array in place. Thus, both the sortedActivities and activities arrays are now sorted. One option to protect the original array from being modified is to use the slice() method to create a copy of the array prior to sorting:

const sortedActivities = activities.slice().sort((a, b) => b.date - a.date)

Lessons in this unit:

0: Introduction
1: Date Basics
2: Getting Date Parts
3: Date Formatting
4: Date Math
5: Date Comparisons
6: ▶︎ Date Recipes