Create a timestamp in JavaScript
Last updated: July 8, 2022.
A timestamp is a record of the precise time at which something occurs.
In JavaScript, current or custom date and time can be converted to a timestamp via the built-in Date()
object constructor. Timestamps can also be used to get time and date.
Table of contents
Generating a timestamp
Current time
The conventional timestamp is known as the UNIX timestamp, which is the number of seconds that have passed since 1st Jan 1970.
The Date()
object constructor can be used to get this timestamp in milliseconds with either a direct method or through creating a new Date
object:
const x = Date.now();
const y = new Date().getTime();
console.log(x); // 1657111698622
console.log(y); // 1657111698622
Then, get convert to the UNIX standard, divide by 1000 and round the result:
const x = Date.now();
const y = new Date().getTime();
Math.floor(x/1000); // 1657112258
Math.floor(y/1000); // 1657112258
There are some alternative ways to generate a UNIX timestamp in milliseconds you may come across.
The first is by calling valueOf()
on a Date
object. This returns its ‘primitive’ value, which works because Date()
works in UNIX time under the hood.
The second is to use the unary operator before create a new Date
object. This works because the unary operator calls the valueOf()
method on an object.
const x = new Date();
x.valueOf(); // 1657116520338
+new Date(); // 1657116520338
For a custom time
You can generate a timestamp from a Date
object set to any date and time.
A Date
object with a custom date and time can be created by passing in a valid time string (ISO 8601 format) or arguments to the Date()
constructor.
Then call the getTime()
method on the result:
// Custom date with string in ISO 8601 format
const x = new Date('2022-07-06T12:38:24Z');
x.getTime() // 1657111104000
// Custom date with arguments: YYYY, MM, DD, HH, MM, SS
const y = new Date(2022,06,05,12,38,24);
y.getTime() // 1657111104000
Usage warning
It is strongly recommended to use numeric arguments to create custom dates with the Date()
constructor where possible.
This is because of inconsistent cross-browser interpretation of string input.
From timestamp to date and time
In case you want to convert a timestamp to the date it represents, you can pass it in to the Date()
constructor and use a method on the new object it creates to view its contents:
const a = new Date(-1657111698622);
console.log(a.toLocaleString('en-US')); // 6/28/1917, 1:11:41 PM
const b = new Date(0);
console.log(b.toLocaleString('en-US')); // 1/1/1970, 1:00:00 AM
const c = new Date(1657111698622);
console.log(c.toLocaleString('en-US')); // 7/6/2022, 2:48:18 PM
Related links
- OpenJavaScript: Getting and formatting date and time in JavaScript
- MDN Web Docs: Standard built-in objects > Date