date.parse string to javascript
- Published
- Reading time
- 2 min read
- Length
- 304 words
On this page
How to Use Date.parse() Function in JavaScript?#
If you are working with JavaScript, you might have come across the use of the Date.parse() function. This function is used to parse a date string and convert it into a date object that can be used for calculations or comparisons.
What is Date.parse()?#
Date.parse() is a built-in JavaScript function that takes a date string as input and converts it into a date object. The date string can be in various formats, such as:
- "2019-10-31"
- "10/31/2019"
- "October 31, 2019"
- "31 Oct 2019"
The function returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, also known as the Unix Epoch. This number can be used to create a new date object or perform calculations.
Using Date.parse()#
To use the Date.parse() function, you simply pass a date string as an argument:
var dateString = "10/31/2019";
var milliseconds = Date.parse(dateString);
console.log(milliseconds); //1572470400000
This code will output the number of milliseconds since the Unix Epoch for the date "10/31/2019".
Multiple Ways to Use Date.parse()#
There are different ways to use Date.parse() depending on your requirements. Here are some examples:
- Passing a date string and a time string:
var dateString = "10/31/2019";
var timeString = "12:30 PM";
var datetimeString = dateString + " " + timeString;
var milliseconds = Date.parse(datetimeString);
console.log(milliseconds); //1572490200000
- Using ISO format:
var isoString = "2019-10-31T12:30:00";
var milliseconds = Date.parse(isoString);
console.log(milliseconds); //1572526200000
- Using UTC time zone:
var dateString = "10/31/2019";
var timeString = "12:30 PM";
var datetimeString = dateString + " " + timeString;
var milliseconds = Date.parse(datetimeString + " UTC");
console.log(milliseconds); //1572479400000
These are just a few examples of how you can use the Date.parse() function. You can experiment and find the format that suits your needs.