2017-07-23 56 views
-1

我有一个格式为YYYYMMDD(20170603)的字符串日期。这个字符串中没有连字符,它只是一个字符串。我想转换这个字符串,以便它可以被日期构造函数使用。我想要做到以下几点new Date(2017,06,03)这样做的最有效方法是什么?注:我希望我的日期是在YYYY MM DD格式为新的日期构造函数转换字符串日期

+0

@SurabhilSergy不,这是不是这样的问题,因为我想我的字符串是它到底是日期格式 – Bytes

+0

4答案,但所有1个错误的方式。相当于“20170603”的是新日期('2017','06' - 1,'03')'。这是许多其他问题的重复。 – RobG

回答

1

你可以只使用字符串():

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

像评论显示,你可以也离开了parseInt函数:

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

该月份需要为-1,* parseInt *是多余的。这是许多其他问题的重复。 – RobG

+0

@RobG你说得对。尽管如此,你需要parseInt。 – dev8080

+0

不需要parseInt。 '-'操作符将参数强制转换为数字,因此''5“ - 1'返回'4'(与'var n =”5“; --n'一样)。 – RobG

0

您可以使用String.prototype.slice()

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

@RobG好点。查看更新后的帖子 – guest271314

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);

+0

该月应该是-1 – RobG