Monday, July 18, 2016

Parse string to date in javascript

How “string” value can be parsed into “date” in javascript?

We can parse date from string using two methods:

Date.parse(datestring)

Or

new Date(dateString)

if dateString is according to the ISO-8601 or RFC2822 standard then it will return the valid converted date otherwise it may result unexpected result.

The Standard format is :YYYY-MM-DDTHH:mm:ss.sssZ

   ·      When we use the date.parse, it internally use the new Date(datestring)

   ·       After successfully parsing the date, it returns the date in the “number of milliseconds” since   January 1, 1970, 00:00:00 UTC.

   ·       In case of Date.parse(dateString) if date is invalid then it will return “NaN” and

   ·       In case of new Date(dateString) if date is invalid then will return “Invalid Date


Examples:

Date.parse("18/07/2016")

//result: NaN

new Date("18/07/2016")

//result: Invalid Date

Date.parse("2016-07-18")

//result: 1468800000000

new Date("2016-07-18")

//Result: Mon Jul 18 2016 05:30:00 GMT+0530 (India Standard Time)

There is one famous javascript library to Parse, validate, manipulate, and display dates in JavaScript.

You can go through it with the below link: