nemo_87
nemo_87

Reputation: 4781

Return date and time in ("YYYY-MM-DD HH:mm") format when using moment.js (timezone)

I am using moment-timezone so I can convert from selected timezone to timezone of a client.

I wasn't able to implement it in a better way than this:

convertSelectedTimeZoneToClients() {
    let timeZoneInfo = {
        usersTimeZone: this.$rootScope.mtz.tz.guess(),
        utcOffset: this.formData.timeZone.offset,
        selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime 
    };

    let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
    let convertedTime = this.$rootScope.mtz.tz(utcTime, timeZoneInfo.usersTimeZone).format("Z");
    return convertedTime;
}

So basically I am using usersTimeZone: this.$rootScope.mtz.tz.guess(), guess() function to find out timezone from the browser. Then I get values from datetime picker and dropdown and convert them to UTC value by using utcOffset. At the end I want to convert that utc value to user timezone value.

I get object like this:

enter image description here

_d represent correct value after conversion. I have tried adding bunch of different .format() paterns on convertedTime variable, but I am not able to retrive time in this format: "YYYY-MM-DD HH:mm". I guess it works differentlly than when using .utcOffset() function.

Can anybody help me with this?

Upvotes: 0

Views: 3874

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241450

You don't need to guess the client time zone to convert to local time. Just use the local function.

For example:

moment.tz('2016-01-01 00:00', 'America/New_York').local().format('YYYY-MM-DD HH:mm')

For users located in the Pacific time zone, this converts from Eastern to Pacific and you get an output string of "2015-12-31 21:00". For users in other time zones, the output would be different, as expected.

You don't need to format to a string and re-parse it, or manually manipulate the UTC offset either. That is almost never warranted.

Upvotes: 2

Related Questions