-1

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

Bytes
  • 691
  • 1
  • 7
  • 22
  • @SurabhilSergy No this is not like that question because I'd like my string to be exactly the way it is in date format – Bytes Jul 23 '17 at 17:45
  • 4 answers, all but 1 wrong. The equivalent of "20170603" is `new Date('2017', '06' - 1, '03')`. This is a duplicate of many other questions. – RobG Jul 23 '17 at 22:41

3 Answers3

1

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 , 
          str.substring(6,8) 
        );
dev8080
  • 3,950
  • 1
  • 12
  • 18
0

You can use String.prototype.slice()

let month = +str.slice(4, 6);
let date = new Date(str.slice(0, 4), !month ? month : month -1, str.slice(6))
guest271314
  • 1
  • 15
  • 104
  • 177
0

var dateStr = "20170603";
var match = dateStr.match(/(\d{4})(\d{2})(\d{2})/);
var date = new Date(match[1] + ',' + match[2] + ',' + match[3])

console.log(date);
caramba
  • 21,963
  • 19
  • 86
  • 127