6

Conversion of the date of the string with the offset to the different time zone

 2 years ago
source link: https://www.codesd.com/item/conversion-of-the-date-of-the-string-with-the-offset-to-the-different-time-zone.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Conversion of the date of the string with the offset to the different time zone

advertisements

I'm wondering on the correct way to convert a string date in a non-ISO format to a different offset/timezone.

I am currently given 3 values:

  • the date in format MM/DD/YYYY (23/11/2016)
  • the time in 24h format (23:13)
  • timezone offset (-07:00)

I would like to convert said date to the user's timezone.

I am trying to convert the format to the format accepted by moment timezone's moment.tz() function ('2016-11-23T23:13-07:00') but I am not sure how to do that without splitting the date array and converting it to said date.

Moment's timezone has the tools I need to convert the date afterwards to the local timezone. For example:

moment.tz('2016-11-23T23:13-07:00', moment.tz.guess());

Any thoughts on how to convert 23/11/2016 23:13 with offset -07:00 to the local date preferably using momentJS?


I like Rob's answer, but I'll also give you it in moment.js.

First, you don't need moment-timezone, and you definitely don't need to guess the time zone id just to convert to that zone. In ISO format, it would just be like this:

var m = moment('2016-11-23T23:13-07:00');

This will read in the offset during parsing, apply it, then convert to the local time zone, returning a moment object in "local mode". This is the default mode, so it just works.

With the requirements you described it would be like this:

// your inputs
var d = "23/11/2016";
var t = "23:13";
var o = "-07:00";

var m = moment(d + ' ' + t + o, 'MM/DD/YYYY HH:mmZ');

Note that I add the space between the date and time just for safety, so there's no risk of mixing the year and the hour components.

Again it will automatically apply the offset and convert to the local time zone, since that's the default behavior. If you want some other behavior, there are ways to do that as well.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK