. Advertisement .
..3..
. Advertisement .
..4..
There are numerous methods to convert string to date in Javascript. However, no matter which method you are choosing, you have to specify the data about the represented dates and times.
Different areas and cultures have their own day, month, and date orders. This article will introduce you to some useful tips to do the task precisely.
How To Convert A String Into A Date In Javascript
Method 1: Use the new Date() Function
The new Date()
function is one of the most commonly used methods to convert a string. It takes various forms of arguments and returns a date object.
With this method, you don’t have to use any parameter as an argument. In this case, the current date and time by default will be returned with the local timezone information.
If you have passed a date object as the argument, you will receive a depicted date object in the string. However, its format should be YYYY-MM-DD
. Other date formats will not work in this method.
Code:
new Date("2021-05-23");
new Date("2020/2/29");
new Date("2020-14-03");
new Date("14-02-2021");
Output:
Sun May 23 2021 05:30:00 GMT+0530 (India Standard Time)
Sat Feb 29 2020 00:00:00 GMT+0530 (India Standard Time)
Invalid Date
Invalid Date
As can be seen from the examples above, only two first code lines can return results as they carry the accepted string format of ISO 8601 standards.
The other two return an Invalid date results. For such different formats. it would be best to split the string and pass them as suitable arguments in the new Date()
function.
Method 2: Use The Date.parse() Function
The Date.parse()
function is another alternative method to convert a string. Yet, instead of returning a date object, it will give you a numeric value.
The parse date will be converted to a number, which represents the milliseconds. The result follows the timestamp format with some small differences. It replaces the seconds with a millisecond value.
Code:
Date.parse("2020-11-21")
Date.parse("2019-01-01T12:30:00.000Z")
Date.parse("20-11-2021")
Date.parse("11-20-2021")
Output:
1605916800000
1546345800000
NaN
1637346600000
The new Date()
and Date.parse()
functions require the same input value type. Yet, the second one checks to give a valid date format. For this reason, it is useful for an API response value. Use the isNaN()
to identify and choose the suitable date conversion method.
Code:
let stringsFromAPI = ["2020-11-21", "20-11-2021"];
stringsFromAPI.forEach( (d) => {
if (!isNaN(Date.parse(d))) {
console.log(new Date(d));
}
})
Output:
Sat Nov 21 2020 05:30:00 GMT+0530 (India Standard Time)
The Date.parse()
one is ideal to compare the precision of dates without converting to the actual date object.
Method 3: Split And Convert String
These two approaches mentioned above are designed items following the ISO 8601 extended date format. Yet, if your format doesn’t obey this standard one, you will have to work with it manually.
All you have to do is to split the string, extract the values, and convert them to the desired format. You can use the new Date()
function to support the new parameters.
Syntax:
new Date(yearValue, IndexOfMonth, dayValue, hours, minutes, seconds)
Parameters:
- yearValue: All items must follow the ISO 8061 YYYY format. Otherwise, the result will return a wrong value.
- IndexOfMonth: The value often starts with 0. Thus, don’t forget to subtract the month value 1 unit. The month index should be between 0 and 11.
- day Value: This parameter indicates the month’s day, which should belong to the range of 1 and 31.
- hours: indicates the hour. For example, 7 o’clock.
- minutes: the minutes in one hour.
- seconds: the seconds in a minute
Code:
function convertFromStringToDate(responseDate) {
let dateComponents = responseDate.split('T');
let datePieces = dateComponents[0].split("-");
let timePieces = dateComponents[1].split(":");
return(new Date(datePieces[2], (datePieces[1] - 1), datePieces[0],
timePieces[0], timePieces[1], timePieces[2]))
}
convertFromStringToDate("21-03-2020T11:20:30")
Output:
Sat Mar 21 2020 11:20:30 GMT+0530 (India Standard Time)
Conclusion
All the methods to convert a string into a date in Javascript will work perfectly with the ISO 8601 date format. Sometimes, the date conforms to another format. In this case, you should split the string, extract the values, and convert them.
Leave a comment