简体   繁体   中英

Convert ISO Date string to date in JavaScript

Need help to convert exactly from ISO Date string to Date: I have an ISO string date: "2016-01-23T22:23:32.927". But when I use new Date(dateString) to convert Date, the result is wrong:

var date = new Date("2016-01-23T22:23:32.927");

The result is: Sun Jan 24 2016 05:23:32 GMT+0700 . It's not true. I want the date is 23 not 24.

Please help me. Thanks a lot!

You need to supply a timezone offset with your iso date. Since there isn't one, it assumes the date to be in GMT and when you log it out, it prints it in the timezone of your browser. I think that if you pass "2016-01-23T22:23:32.927+07:00" to new Date() you would get the value you are expecting.

JavaScript environments (browser, node,...) use a single timezone for formatting dates as strings. Usually this is your system's timezone. Based on the output you get, yours is GMT+0700.

So what happened:

  • The string you passed as ISO format to the Date constructor doesn't specify a timezone. In this case it is treated as UTC.
  • When you then output the date (I'll assume with console.log ), it is converted to the timezone of your environment. In this case 7 hours where added.

If that doesn't suit you, you can change the way you output the date. This depends on what output you want, eg:

  • If you just want the UTC timezone again, you can use date.toISOString() .
  • If you want to output it in another timezone, you can call date.getTimezoneOffset() and figure out the difference between both timezones. You'd then probably need to get the individual date parts and add/subtract the timezone difference accordingly. At this point you could consider using an existing library, taking into account their possible disadvantages.

使用date.toUTCString()它将得到23而不是24,因为它根据通用时间将日期对象转换为字符串

If you're willing and able to add a dependency, I recommend using moment.js for this. It makes date handling in Javascript much more straightforward and a lot safer, and fixes your specific problem right out of the box.

To do this, 1st load it from a CDN, eg Moment.JS 2.14.1 minified . Then use it as follows:

var date = moment("2016-01-23T22:23:32.927");
console.log(date);
// output:  Sat Jan 23 2016 22:23:32 GMT-0500

...ie your desired result :)

Here's a jsfiddle demonstrating this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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