Table of Contents
If we want to discuss the timestamp in JavaScript, we have to discuss the timestamp first.
A timestamp is a non negetive numeric representation of the current time. It’s one-of-a-kind and signifies a very specific identification that pinpoints the exact moment when an event or action occurred.
There are several uses for this timestamp, including logging, debugging, and time interval measurement. We will cover every scenario and method for obtaining a timestamp in JavaScript in this tutorial.
Using Date.now() Method
The Date.now() method is a static method of the Date object. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC (coordinated universal time). It is often referred to as a Unix timestamp.
Since it’s a static method, we can call it directly without initialization, and it’s widely supported by modern browsers. Here is the code to get a timestamp in JavaScript using the Date.now() method:
<script>
const timestamp_now = Date.now();
console.log('Javascript timestamp: '+timestamp_now);
</script>
Output
This will output a single number that represents the current date and time, like a Unix timestamp.
Code Explanation of Timestamp in JavaScript
In this example, the JS variable timestamp_now will hold the current timestamp in milliseconds returned by the Date.now() method. The console.log then prints the current timestamp.
Convert Timestamp in Seconds
If we want the timestamp in seconds, then we can easily achieve this by dividing the return value of Date.Now() by 1000. Let’s check how we can get the current JavaScript timestamp in seconds:
<script>
var timestamp_now = Date.now();
timestamp_now = timestamp_now/1000; // javascript timestamp in seconds
console.log('Javascript timestamp: ' + Math.floor(timestamp_now));
//OR
console.log('Javascript timestamp: ' + Math.floor(Date.now() / 1000));
//OR
console.log('Javascript timestamp: ' + ((Date.now() / 1000) | 0));
</script>
Output
The above code will return a numeric value (which may be in a float due to milliseconds to seconds conversion). You can format this JS timestamp using the floor or ceil method.
Code Explanation
In this code example, the JS variable timestamp_now will hold the current timestamp in milliseconds returned by the Date.now() method.
Then we do a conversion from milliseconds to seconds to get the timestamp in seconds. Optionally, you can round up the timestamp as per your needs.
The console.log then print the current timestamp in the JS console.
Using Date.prototype.valueOf() Method
The Date.prototype.valueOf() method also returns the primitive value of a Date object, which is the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC (coordinated universal time). It’s also a Unix timestamp.
Code Example #1
<script>
const timestamp_now = new Date().valueOf();
console.log('Timestamps javascript:' + timestamp_now);
</script>
Output
Code Example #2
Alternatively, we can use the JS unary operator + to call Date.prototype.valueOf:
<script>
const timestamp_now = + new Date();
console.log('Timestamps javascript:' + timestamp_now);
</script>
Output
What’s the use of the plus sign? In JS, + is used as a replacement for toInt() to ignore all the characters and get only the numbers. A lot of developers like this shorter form of code, which is also supported by all modern browsers.
More precisely, it’s basically a shorter version of code to replace the new Date().valueOf() method without calling the JS function. But don’t write it this way, because it affects your code’s readability.
How to Get UNIX Timestamp in Seconds Using Date().valueOf() Method
To get a JavaScript timestamp in seconds, always divide the millisecond value by 1000, as discussed in the earlier section. Later on, use JS numeric rounding functions in the following way:
<script>
var unix_timestamp_seconds_v1 = Math.round(new Date().valueOf()/1000);
console.log('Timestamps javascript V1:' + unix_timestamp_seconds_v1);
//Shorter code version
var unix_timestamp_seconds_v2 = Math.round(+new Date()/1000);
console.log('Timestamps javascript V2:' + unix_timestamp_seconds_v2);
</script>
Output
Using New Date().getTime() Method
This Date().getTime() JS method also returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. It’s not a static method; rather, it’s an instance method of the Date object. This method is equivalent to the valueOf() method.
Code Example
<script>
//Retrun miliseconds
var unix_timestamp = new Date().getTime();
console.log('UNIX Timestamps javascript:' + unix_timestamp);
</script>
Output
Timestamp in Seconds Using New Date().getTime() Method
As new Date().getTime() method always returns milliseconds, so we have to convert it into seconds. JS rounding functions are also required here. Please follow our previous 2 mentions.
IE8 and Earlier Browser Supported Issue
The JS Date.now() static method does not support IE8 and earlier browser versions. To make it workable, we have to create a shim for this method. Like:
<script>
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
</script>
Security Issue – Performance.now vs. Date.now
The Date.now() method is always dependent on the system clock. Possibly impacted by the system, user clock changes, clock skew, etc., as it’s always return Unix epoch (1970-01-01T00:00:00Z).
To overcome this issue, we can use the performance.now() method to ensure highly accurate timestamps in JS. It’s using the timeOrigin property. Now the question is: what is it? Basically, the timeOrigin property is a monotonic clock. It guarantees us that no user adjustment can change the javascript timestamp if you use the performance.now() method.
Get a High Resolution Timestamp in Milliseconds and Why it’s Necessary?
As discussed earlier, the monotonic clock gives us the guarantee to generate an accurate timestamp in JS. Here’s how:
<script>
var bPerformanceSupported = (
window.performance &&
window.performance.now &&
window.performance.timing &&
window.performance.timing.navigationStart
);
var timeStampInMs = (
bPerformanceSupported ?
window.performance.now() +
window.performance.timing.navigationStart :
Date.now()
);
console.log(timeStampInMs, Date.now());
</script>
Output
So we strongly recommend using the performance.now() method if you have to implement a critical timestamp for your application. This process is a much safer option against time-tempering issues.
Use Cases of Timestamp in JavaScript
OK, so far we have read about how to get a timestamp in JavaScript. Now we are going to discuss the use cases where we are bound to use the JS timestamps. We know that you are here for one reason, but we would like to broaden your knowledge of different scenarios in which you can also use the JS timestamps. So, let’s start:
API Level Communication: More often than not, we have to send or receive timestamp values during API communication. Such as chat applications, where both-way messaging and timekeeping are required.
Log Events: As we know, logging events for further analysis is a common task for every developer or a common requirement for every application. It’s also obvious to track when the event actually occurred and what the event details are.
Compare Date and Time: Almost in every application, we are working with date and time. Thus, comparing dates is undeniable. By converting datetime into timestamps, you can easily compare them. And it’s also a good practice.
Measure Execution Time: To get the execution time of a process, we must measure the execution start time and end time. Later on, we pick up the differences and get the original execution time.
As timestamps keep track of milliseconds, it is always recommended to collect start and end timestamps. It’s very useful for performance monitoring or tracking the execution time of a process.
Considerations of JavaScript Current Timestamp
- For critical timestamp measurements, use the performance.now() method.
- JS timestamps always return milliseconds. So if you need seconds, then you have to convert it and divide by 1000.
- If you have a more critical timestamp requirement for different time zones, we suggest using third-party tools such as Moment.js. It will give you extra features to handle the date time or timestamps easily.
- If you are unable to use a third-party tool, then at least use UTC methods like getUTCDate() and etUTCMonth(). These are the UTC methods, which return values in UTC, not local time. It’ll also help you avoid time zone-related issues and daylight saving time.
Conclusion
How do I get a timestamp in JavaScript? In summary, we can get a timestamp in JS using the Date.now() method or the getTime() method commonly. We have also discussed a lot more ways based on different considerations. We have also enlisted every possible use case, along with risks and mitigations.
Though performance.now() is an advanced method, we have tried our best to make it easier for our readers.
We also suggested using third-party tools in cases of necessity, especially to avoid different time zone-related issues.
I hope you get an overall idea of getting a timestamp in Javascript. If so, please leave a comment and help us to improve ourselves.
FAQs on Timestamp in JavaScript
JavaScript timestamp number is not unique. What to do?
The methods Date.now(), Date.prototype.valueOf(), and Date().getTime() all return the number of milliseconds. But here is a catch: The returned values are not unique. If you try to execute these methods multiple times to get a timestamp in Javascript, you may end up with the same value again and again.
Now the question is: Why is this number not unique? And how do we get a unique timestamp number from the current date and time?
The answer is to use Math.random() and not use any of the Date() APIs. Such as:
var jsTimestamp = new Date().getTime() + Math.random();
By using this easy technique, you will get relief soon. But in recent days, all modern browsers have been able to use the performance.now() method. This API ensured that each and every call’s return had a unique value. You did not get any duplicate values.
What JavaScript data type is used to store a timestamp?
The best data types in JS to store timestamp values are BigInt, Float, and Double. But it’s best to use var or const if you are not going to compare timestamps in JS.
How to use JavaScript timestamp?
The four most widely used use cases are API-level communication, log events, compare date and time, and measure execution.
What is the difference between JavaScript timestamp and Unix timestamp?
The main difference is that JavaScript timestamps are in milliseconds, whereas UNIX timestamps are in seconds since the Unix epoch.
What is the difference between datetime and timestamp?
JavaScript Datetime is a date object and a primitive data type in JS, whereas timestamp is a non-negative numerical value type.
Can we compare date and timestamp?
No, you cannot do it directly. You have to convert to the same type first.
Is timestamp equal to datetime?
Yes, it’s the same. But there is one difference. JS datetime can store a longer range of values than a timestamp. The datetime min range is ‘1000-01-01 00:00:00.000000’ and the max range is ‘9999-12-31 23:59:59.999999’, whereas the timestamp can store values starting from ‘1970-01-01 00:00:01.000000’ to ‘2038-01-19 03:14:07.999999’.
What is the format for timestamp?
Timestamp accepts the format ‘yyyy‑MM‑dd HH:mm:ss. SSSSSS’, and can comprise of just a date or just a time. The second part is optional, and it depends on which method you are using to get the timestamp value.
How to resolve timeStamp.getDate is not a function?
const timeStamp_now = ‘1352377138377’;
console.log(timeSince(timeStamp_now));
Here, timeStamp_now is a string. It needs to be converted to a date type to access date methods such as getDate(). Look at the below workaround:
const timeStamp_now = new Date(parseInt(‘1352377138377’));
console.log(timeSince(1352377138377));
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply