Last updated: Mar 6, 2024
Reading timeยท2 min
Use the getTime()
method to convert an ISO date to a timestamp.
The getTime
method returns the number of milliseconds since the Unix Epoch
and always uses UTC for time representation.
const isoStr = '2022-07-21T09:35:31.820Z'; const date = new Date(isoStr); const timestamp = date.getTime(); console.log(timestamp); // ๐๏ธ 165839613182
We used the Date() constructor
to parse an ISO string and get a Date
object.
The getTime() method returns the number of milliseconds between the 1st of January, 1970 and the given date.
getTime
method always uses UTC for time representation. In other words, the time zone of the visitor's browser doesn't change the value the method returns.If you need to remove the offset from the timestamp, use this approach instead.
const isoStr1 = '2022-07-21T09:35:31.820Z'; const date = new Date(isoStr1); const timestampWithOffset = date.getTime(); const offset = date.getTimezoneOffset() * 60 * 1000; console.log(offset); // ๐๏ธ -10800000 const timestampWithoutOffset = timestampWithOffset - offset; const dateWithOffset = new Date(timestampWithOffset); console.log(dateWithOffset); // ๐๏ธ Thu Jul 21 2022 12:35:31 GMT+0300 const dateWithoutOffset = new Date(timestampWithoutOffset); console.log(dateWithoutOffset); // ๐๏ธ Thu Jul 21 2022 15:35:31 GMT+0300
The getTimezoneOffset() method returns the difference, in minutes, between a date (evaluated in UTC) and the same date evaluated in the visitor's local time zone.
If you get a value like -120
, then the time zone offset is UTC+02.
Similarly, for a value of -60
, the time zone offset is UTC+01.
The getTime()
method can also be used to copy the date and time from one
Date
object to another.
const isoStr = '2022-07-21T09:35:31.820Z'; const date = new Date(isoStr); console.log(date); // ๐๏ธ Thu Jul 21 2022 12:35:31 GMT+0300 const timestamp = date.getTime(); console.log(timestamp); // ๐๏ธ 165839613182 const dateCopy = new Date(timestamp); console.log(dateCopy); // ๐๏ธ Thu Jul 21 2022 12:35:31 GMT+0300
Cloning a Date
object is very useful when you want to avoid mutating it in
place with some of the set*
methods, e.g. setHours()
.
You can also use the getTime
method to compare dates.
const isoStr1 = '2022-07-21T09:35:31.820Z'; const isoStr2 = '2023-04-24T10:30:00.820Z'; const date1 = new Date(isoStr1); const date2 = new Date(isoStr2); console.log(date1.getTime() > date2.getTime()); // ๐๏ธ false console.log(date1.getTime() === date2.getTime()); // ๐๏ธ false console.log(date1.getTime() < date2.getTime()); // ๐๏ธ true
The examples show how to compare dates using their Unix timestamp.
You can learn more about the related topics by checking out the following tutorials: