简体   繁体   English

将ISO日期字符串转换为Date对象而不考虑时区

[英]Convert ISO date string to Date Object without considering timezone

Goal: Convert ISO date string to Date Object without considering timezone 目标:不考虑时区,将ISO日期字符串转换为Date对象

I have a ISO string: 2017-07-23T20:30:00.00Z. 我有一个ISO字符串:2017-07-23T20:30:00.00Z

I tried converting that string to Date with the following methods: 我尝试使用以下方法将该字符串转换为Date:

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) 所有人均提供以下输出:Mon Jul 24 2017 02:00:00 GMT + 0530(印度标准时间)

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. 只需在末尾删除“ Z”字符就可以解决问题。

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. 发生这种情况是因为“ Z”字符在使用格式时不会导致时间被视为UTC。 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. 通过在括号中指定“ Z”,您将匹配文字Z,因此时区保留在当前的默认值,即本地时区。

You should always specify the parse format. 您应该始终指定解析格式。 In this case, just leave off the "Z": 在这种情况下,只需省略“ 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> 

Try this 尝试这个

var date = new Date('2017-07-23T20:30:00.00Z');
console.log(date.getFullYear()+'/' + (date.getMonth()+1) +
 '/'+date.getDate());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM