Get Parseable Timezone

AlbertEngelB

I am using Momentjs and Momentjs Timezone to handle dates / timezones.

I'm attempting to have a date that is input from a user in a specific time zone and convert it to the local time in their own time zone. It doesn't look like Moment's Timezone library supports the new Date().getTimezoneOffset() format for setting the time zone.

function calculateLocalTime(e) {
  var currentTz = new Date().getTimezoneOffset(),
      fromDate = moment.tz(this.value, 'GMT'),
      toDate = fromDate.tz(currentTz);

  $('to-time').val(toDate.format(dateFormat));
}

I've also attempted to extract the three-letter time zone from the normal Date object as well, but that doesn't seem to be supported either.

function calculateLocalTime(e) {
  var currentTz = new Date().toString().split(' ').pop().replace(/\(/gi, '').replace(/\)/gi, ''),
      fromDate = moment.tz(this.value, 'GMT'),
      toDate = fromDate.tz(currentTz);

  $('to-time').val(toDate.format(dateFormat));
}

Any idea on how I should be doing this using Moment?

Matt Johnson-Pint

Moment-timezone is for working with standard identifiers from the IANA TZ Database, such as America/Los_Angeles.

Moment.js supports fixed-offset zones, independent of moment-timezone, using the zone function.

var m = moment();

// All of the following are equivalent
m.zone(480);        // minutes east of UTC, just like Date.getTimezoneOffset()
m.zone(8);          // hours east of UTC
m.zone("-08:00");   // hh:mm west of UTC  (ISO 8601)

However, since you said you wanted to convert to the user's local time zone, there's no need to manipulate it explicitly. Just use the local function.

Here is a complete example, converting from an explicit IANA time zone to the user's local time zone:

// Start at noon, Christmas Day, on Christmas Island (in the Indian Ocean)
var m = moment.tz('2014-12-25 12:00:00', 'Indian/Christmas');

// Convert to whatever the user's local time zone may be
m.local();

// Format it as a localized string for display
var s = m.format('llll');

For me, running this in the US Pacific time zone, I get "Wed, Dec 24, 2014 9:00 PM". The result will vary depending on where the code is run.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related