JavaScript

Convert ISO Date to Milliseconds Using getTime() Method in JavaScript

The ISO standard adopts a general-to-specific strategy for its date format. Where the year is always stated first, the days of the month come next, with the majority of the elements being represented by numerical values, then the month. The ISO date representation for (July 21, 1996) is either “19960721” or “1996-07-21”. There arises the need some times to convert the date into milliseconds. For that purpose, JavaScript provides a “getTime()” Method for its programmers.

This post will explain the method for converting/modifying the ISO date to milliseconds in JavaScript.

How to Convert an ISO Date to Milliseconds?

To convert the ISO date to milliseconds in JavaScript, different methods can be invoked, including “getTime()”, “getTimezoneOffset()”, etc. However, this post will specifically discuss the usage of the getTime() method.

Syntax

Utilize the following syntax to convert ISO date into milliseconds using the getTime() function:
date_val.getTime();

Replace the “date_val” with any valid ISO date that needs to be converted into milliseconds.

Return Value
The “getTime()” returns a numeric value representing the given Date-Time in milliseconds since the Epoch (i.e. January 1st, 1970).

Let’s comprehend the usage of the getTime() function using the following example.

Example: Convert ISO Date to Milliseconds Using the “getTime()” Method
Users can use the “getTime()” method to convert the ISO date into milliseconds.

To demonstrate how the getTime() Method works, use the “Date()” method, call it and supply the date as a parameter. Then, store it in the variable:

var date = new Date("03/5/2023 19:00:00");

Initialize a variable “ms” and apply the “getTime()” method on the “date”. It will return the milliseconds:

var ms = date.getTime();

Invoke the “console.log()” method and pass the defined variable as the argument of the method to display the result on the console:

console.log(ms);

It can be noticed that the date is converted into milliseconds in JavaScript:

That’s all about converting the ISO date to milliseconds in JavaScript.

Conclusion

To convert the ISO date to milliseconds in JavaScript, the “getTime()” method is used. It retrieves a numeric value representing the given Date-Time in milliseconds since the Epoch (i.e. January 1st, 1970). This tutorial has demonstrated the procedure for converting the ISO date to milliseconds using JavaScript’s “getTime()” method.

About the author

Hafsa Javed