Get a UTC timestamp in Javascript
Javascript timestamp can be obtained by using a method called getTime which is availabled on Date object.
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 your tiny little flat in New York or a co-working space in Berlin. It always returns the same UTC timestamp.
The method returns the same UTC timestamp from any time zone.
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"
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).
// Date Thu Sep 22 2022 20:45:42 GMT+0200
const date = new Date()
const utcYear = date.getUTCFullYear()
console.log(utcYear) // ๐๏ธ 2022
// Is zero-based! Starts from 0-11
const utcMonth = date.getUTCMonth()
console.log(utcMonth) // ๐๏ธ 8
// Name of the method may be a bit confusing
const utcDay = date.getUTCDate()
console.log(utcDay) // ๐๏ธ 22
const utcHours = date.getUTCHours()
console.log(utcHours) // ๐๏ธ 18
const utcMinutes = date.getUTCMinutes()
console.log(utcMinutes) // ๐๏ธ 45
const 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).
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.
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