Strip Time Zone from string using JavaScripty, Moment.js etc.?

Suppose I have a line like "22/01/2012 2:07:00 PM -08: 00".

I want to

  • a) Format it in ISO 8601 with time offsets from UTC http://goo.gl/JTfAZq , so it will become "2014-01-22T14: 07: 00-08: 00"
  • b) Change the offset time part so that it becomes "01/22/2012 2:07:00 PM" [and then formatted it to ISO 8601 so that it becomes "2014-01-22T14: 07: 00]]

Of course, I can use JavaScript string functions (and regular expressions), but this seems to be the best approach to using JavaScript Date () or Moment.js objects. However, neither work nor work. Both will automatically convert dates to the current system time zone (-05: 00 for me), so 14:07 PM will be 5:07 pm. I found two ways to do this: β€œcross out time, then format” the task, but both look ugly and fragile:

var mydateTime = "01/22/2014 2:07:00 PM -08:00"; // strip out time offset part using substring() so that Moment.js // would think time is specified in a current zone var myNewDateTime1 = moment(mydateTime.substring(0, mydateTime.length - 7)).format("YYYY-MM-DDTHH:mm:ss") // or probably even worse trick - strip out time offset part using format var myNewDateTime2 = moment(mydateTime, "MM/DD/YYYY h:mm:ss A").format("YYYY-MM-DDTHH:mm:ss") 

I understand that the JavaScript Date () object is not intended to preserve the time zone, but there is no more elegant and stable solution for a) and b)?

+6
source share
1 answer

I think you are looking for moment.ParseZone . It analyzes the moment AND saves the time zone offset that was in the line, instead of converting it to the local time zone of the browser.

Also, your myDateTime variable myDateTime not match what you requested. If you really have the full ISO8601 extended with the time zone offfset, then it looks like this:

 var m = moment.parseZone("2014-01-22T14:07:00-08:00"); 

Or, if he, like you initially, showed, then like this:

 var m = moment("01/22/2014 2:07:00 PM -08:00", "MM/DD/YYYY h:mm:ss AZ").parseZone(); 

From there, you can format it as you like:

 var s = m.format("YYYY-MM-DDTHH:mm:ss"); 
+7
source

All Articles