Time in JavaScript

JavaScript offers extensive support for dates and times; here are some examples.

// We'll start by getting the current time.
const now = new Date();
console.log(now);

// You can create a Date object by providing the year, month, day, etc.
// Note that months are 0-indexed in JavaScript (0-11).
const then = new Date(Date.UTC(2009, 10, 17, 20, 34, 58, 651));
console.log(then);

// You can extract the various components of the date value as expected.
console.log(then.getUTCFullYear());
console.log(then.getUTCMonth() + 1); // Adding 1 to get 1-12 range
console.log(then.getUTCDate());
console.log(then.getUTCHours());
console.log(then.getUTCMinutes());
console.log(then.getUTCSeconds());
console.log(then.getUTCMilliseconds());
console.log(then.toUTCString());

// The day of the week (0-6) is also available.
console.log(then.getUTCDay());

// These methods compare two dates, testing if the
// first occurs before, after, or at the same time
// as the second, respectively.
console.log(then < now);
console.log(then > now);
console.log(then.getTime() === now.getTime());

// To get the difference between two dates, subtract them.
// The result is in milliseconds.
const diff = now - then;
console.log(diff);

// We can compute the length of the duration in
// various units.
console.log(diff / (1000 * 60 * 60)); // Hours
console.log(diff / (1000 * 60)); // Minutes
console.log(diff / 1000); // Seconds
console.log(diff); // Milliseconds

// You can add or subtract milliseconds to a date
// to move forwards or backwards in time.
console.log(new Date(then.getTime() + diff));
console.log(new Date(then.getTime() - diff));

To run this JavaScript code, you can save it in a file (e.g., time.js) and execute it using Node.js:

$ node time.js
2023-05-24T12:34:56.789Z
2009-11-17T20:34:58.651Z
2009
11
17
20
34
58
651
Tue, 17 Nov 2009 20:34:58 GMT
2
true
false
false
425921498138
118311.52726055555
7098691.635633333
425921498.138
425921498138
2023-05-24T12:34:56.789Z
1996-05-11T04:34:58.651Z

In JavaScript, the Date object is used to work with dates and times. It provides methods to create, manipulate, and format dates. Unlike some other languages, JavaScript doesn’t have separate types for date and time - everything is represented using the Date object.

The Date object always represents a date-time combination in UTC, but provides methods to work with the date in the local time zone as well. In this example, we’ve used UTC methods to closely match the behavior of the original Go code.

JavaScript measures time in milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC), which is why some operations (like getting the difference between dates) result in millisecond values.

Next, we’ll look at working directly with Unix timestamps in JavaScript.