简体   繁体   中英

Convert Javascript date to UTC with timezone information

I have a UI that allows a user to create an event. When the user creates this event they select a date( and time) and separately they select a timezone (eg. 'America/New_York') for the event location.

I need to use the date (includes time) and the selected timezone (string) to create a UTC date. I'm not sure how to do this.

I thought about using getTimezoneOffset but doesn't this change depending on the time of year ( British Summer Time etc).

Update. I wasn't very clear in my explanation, so here is more detail:

User selects date and time of an event that is 'Jan 01 2017 07:00:00'. They then select the timeZone of 'America/New_York'. It's happening at 7am in New York but I'm in the UK.

When I do:

const formatDate = moment.tz( new Date('Jan 01 2017 07:00:00'), 'America/New_York' ).format(); //returns '2017-01-01T02:00:00-05:00'

if I convert this date in new york to my local date with:

new Date( formatDate ); // returns 'Sun Jan 01 2017 07:00:00 GMT+0000 (GMT)'

I want it to return a local date and time of 'Sun Jan 01 2017 12:00:00 GMT+0000 (GMT)'.

From docs :

If you want an actual time zone -- time in a particular location, like America/Los_Angeles , consider moment-timezone .

This suggests the feature is not built-in into Moment.js itself but the other library should get it done:

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

Beware that you should still store the named time zone in another column, because there's no way to deduct it from the date stored in MySQL.

I did it in the end with the following:

const momentTimezone = require( 'moment-timezone' );
const DateWithOffset = require( 'date-with-offset' );

module.exports = function( date, timezone ) {

    const offset = momentTimezone.tz.zone( timezone ).offset( date );

    const newDate = new DateWithOffset( date.toUTCString(), ( 0 - offset ) );

    return newDate.toISOString();

};

There may be a better way of doing this, but this seems to work. I used the npm module date-with-offset which did the job required.

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