Modify timezone new date javascript [duplicate]

2019-08-09 09:31发布

问题:

This question is an exact duplicate of:

  • How do I combine moment.js timezone with toDate to build a new date object? 1 answer

I'm using a calendar plugin in which I want the Date object to be stored with a particular timezone. I am using the plugin, moment.js and moment-timezone.js.

console.log(new Date(moment.tz("2012-11-04 01:00:00-04:00", "America/New_York").format()));

Obtain: Date {Sun Nov 04 2012 05:00:00 GMT+0000}

I need: Date {Sun Nov 04 2012 05:00:00 GMT-0400}

I'm using a PhoneGap library and I need two object date.

window.plugins.calendar.createEvent(title, event_location, notes, start_date, end_date, function(message) { }, function(message) { });

The plugin save the event in the device calendar and detects if the timezone that is sent is different from the device timezone and changes the timezone of the event. Showing the event time of the event in the timezone of the device and the event.

回答1:

What you asked is not possible. The Date object cannot present any time zone other than the local time zone where the code is running.

Also, if you already have the correct local date, time, and offset, then there's little benefit of using moment-timezone. Simply use parseZone to retain the offset that was given:

console.log(moment.parseZone("2012-11-04 01:00:00-04:00").format());
// "2012-11-04T01:00:00-04:00"