Bytes Bytes - 3 years ago 142
Javascript Question

Converting string date for new date constructor

I have a string date with the format YYYYMMDD (20170603). There are no hyphens in this string, it is just one string. I want to convert this string so it can be used by a date constructor. I want to do the following

new Date(2017,06,03)
What is the most efficient way of doing this? Note: I want my date to be in YYYY MM DD format

Answer Source

You could just use substring():

new Date( parseInt( str.substring(0,4) ) , 
          parseInt( str.substring(4,6) ) -1 , 
          parseInt( str.substring(6,8) ) 

Like the comments show, you could well leave out the parseInt:

new Date( str.substring(0,4) , 
          str.substring(4,6) - 1 , 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download