Convert ISO date string to Date Object without considering timezone

Goal: Convert ISO date string to Date Object without considering timezone

I have a ISO string: 2017-07-23T20:30:00.00Z.

I tried converting that string to Date with the following methods:

new Date('2017-07-23T20:30:00.00Z')

 moment('2017-07-23T20:30:00.00Z').toDate()

 moment.utc('2017-07-23T20:30:00.00Z').toDate()

All are giving the following output: Mon Jul 24 2017 02:00:00 GMT+0530 (India Standard Time)

which is incorrect.

Can you let me know how to get the exact date what was there in string?


Simply removing the 'Z' character at the end should do the trick for you.

Doing the following will print:

moment('2017-07-23T20:30:00.00').toDate();
// Sun Jul 23 2017 20:30:00 GMT+0300 (GTB Daylight Time)

While this for me prints:

moment('2017-07-23T20:30:00.00Z').toDate();
// Sun Jul 23 2017 23:30:00 GMT+0300 (GTB Daylight Time)

This happens because 'Z' character does not cause the time to be treated as UTC when used in the format. It matches a timezone specifier.

By specifying 'Z' in brackets, you are matching a literal Z, and thus the timezone is left at moment's default, which is the local timezone.


You should always specify the parse format. In this case, just leave off the "Z":

var s = '2017-07-23T20:30:00.00Z';
var m = moment(s, 'YYYY-MM-DDTHH:mm:ss'); // <-- parse format without Z
console.log(m.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

尝试这个

var date = new Date('2017-07-23T20:30:00.00Z');
console.log(date.getFullYear()+'/' + (date.getMonth()+1) +
 '/'+date.getDate());
链接地址: http://www.djcxy.com/p/46596.html

上一篇: 日期计算错误

下一篇: 将ISO日期字符串转换为日期对象,而不考虑时区