Get a UTC timestamp in JavaScript
JavaScript timestamp can be obtained by using a method called getTime which is availabled on Date object.
Get a UTC timestamp in JavaScript
As said, the getTime() can be called on Date object, i.e. you can get the UTC timestamp by calling new Date().getTime(). This method returns a number of milliseconds since the Unix Epoch.
In the example below, we're using Date.getTime to get a UTC timestamp.
const utcInMilliseconds = new Date().getTime()console.log(utcInMilliseconds) // 👉️ 1663871087674
It doesn't matter whether you call the method from a Starbucks in New York or a co-working space in Sydney. It always returns the same UTC timestamp.
The method returns the same UTC timestamp from any time zone.
Get a UTC string in JavaScript
To obtain the UTC representation of a date instead of number in milliseconds, use the toUTCString() method.
const utcDateString = new Date().toUTCString()console.log(utcDateString) // 👉️ "Thu, 22 Sep 2022 18:31:10 GMT"
The difference between GMT and UTC
GMT and UTC share the same current time, so what's the difference between these two?
In a nutshell, GMT is a time zone and UTC is a time standard. In fact, UTC is the standard for time zones worldwide.
Keep in mind that the both GMT and UTC don't change for Daylight Saving Time (DST).
Other methods for getting UTC specific parts of the date and/or time
// Date Thu Sep 22 2022 20:45:42 GMT+0200const date = new Date()const utcYear = date.getUTCFullYear()console.log(utcYear) // 👉️ 2022// Is zero-based! Starts from 0-11const utcMonth = date.getUTCMonth()console.log(utcMonth) // 👉️ 8// Name of the method may be a bit confusingconst utcDay = date.getUTCDate()console.log(utcDay) // 👉️ 22const utcHours = date.getUTCHours()console.log(utcHours) // 👉️ 18const utcMinutes = date.getUTCMinutes()console.log(utcMinutes) // 👉️ 45const utcSeconds = date.getUTCSeconds()console.log(utcSeconds) // 👉️ 42
If you need a complete list of the UTC getter methods, please check them out on MDN docs.
These methods help you get various information from the date/time. Beware of inconsistency (naming) of these methods - especially the plurals/singulars and keep in mind that getUTCMonth() is zero-based (starts from 0, i.e. date in January would return 0).
Non-UTC equivalents
For a summary, all getUTC* methods return the date/time information according to universal time. No matter the timezone from which you're calling these methods, you'll always get the same output.
On the other hand, the get* equivalent methods return the date/time according to a local timezone.
Quick tips
- Use local time when displaying the date/time information to the user
- Store the actual date/time in UTC in your DB
- Beware the inconsitencies in UTC getter methods
- Non-UTC getter methods always return date/time according to the local time