How do I get a timestamp in JavaScript?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In JavaScript, you can get the current timestamp in several ways, depending on what you need. Here are the most common methods:
1. Using Date.now()
The simplest way to get the current timestamp in milliseconds since the Unix epoch (January 1, 1970) is by using Date.now():
Date.now()returns the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 UTC.
2. Using new Date().getTime()
Another way to get the timestamp is by creating a new Date object and calling the getTime() method:
new Date().getTime()provides the same result asDate.now(), giving you the current timestamp in milliseconds.
3. Using new Date().valueOf()
You can also use the valueOf() method, which returns the primitive value of the Date object, which is the same as the timestamp in milliseconds:
4. Using +new Date()
You can get the timestamp by using the unary plus (+) operator with a Date object, which converts the Date object into a number (milliseconds since the Unix epoch):
5. Getting a Timestamp in Seconds
If you need the timestamp in seconds (instead of milliseconds), you can divide the result by 1000 and use Math.floor() to remove the decimal part:
Summary
Date.now(): The most straightforward way to get the current timestamp in milliseconds.new Date().getTime(): Another way to get the current timestamp in milliseconds.+new Date(): A concise alternative to get the timestamp in milliseconds.- Seconds: Use
Math.floor(Date.now() / 1000)for a timestamp in seconds.
All these methods give you the current timestamp, and you can choose the one that best fits your coding style or specific needs.
Related reading
- How do I include a JavaScript file in another JavaScript file?
- How do I make the first letter of a string uppercase in JavaScript?
- How do I replace all occurrences of a string in JavaScript?
- How to access the index value in a 'for' loop?
- How to disable text selection highlighting
- Is there an "exists" function for jQuery?
- JavaScript closure inside loops – simple practical example
- Loop (for each) over an array in JavaScript
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.