简体   繁体   中英

Format ISO 8601 date string to 0:00AM with javascript

I have the following ISO 8601 date string:

var isoDate = 2013-10-01T09:00:00.000-04:00;

When attempting to format the date using the Date() function, the timezone of the date changes to my local timezone (note how it's 08:00 instead of 09:00 )

Date.fromISOString(isoDate);  /* Returns: Tue Oct 01 2013 08:00:00 GMT-0500 (Central Standard Time)*/

I want to keep the original timezone of the current string completely in-tact.

If the string has 09:00 , I want to output 9PM .

What is the most conventional way of doing this?

NOTE: I've also tried using datejs with no luck. Trying the following returned a blank result:

Date.parse('2013-10-01T09:00:00.000-04:00')

Use the new operator, the Date constructor, the toISOString method, and multiple string substitutions to preserve the original string:

var foo = "2013-10-01T09:00:00.000-04:00";
var bar = foo.substr(-6);
var baz = foo.substr(11,2)
var isoDate = new Date(foo).toISOString().replace("Z",bar).replace(/T../,"T"+baz);
var hours = String(baz).concat(Number(baz) < 12 ? "PM" : "AM").replace(/^0/,"")

References

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