2017-07-23 57 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