Home > Software engineering >  Converting date/time to a different timeZone using MST7 or AST4 formats
Converting date/time to a different timeZone using MST7 or AST4 formats

Time:10-04

I will get timeZone from the backend in the form of MST7 or AST4 I have to convert current user time to this timeZone I am trying to do something like this

import moment from 'moment-timezone';
.....
const convertedTime = moment.tz(new Date(), 'AST4').format('YYYY-MM-DDTHH:mm:ss');

But I see that moment is not accepting formats MST7 or AST4 and similar other US timeZone in ths format.

Please let me know how I can convert to different USA timesZones by using these formats like MST7 or AST4 etc

CodePudding user response:

The timezones you're supplied with are valid IANA generic timezones (see TZ List).

You can use the moment.tz constructor to create these as with other IANA zones:

const timeZones = ['EST5EDT', 'CST6CDT', 'MST7MDT', 'PST8PDT'];

console.log('Timezone'.padEnd(20), 'Current Time');
for(let timeZone of timeZones) {
    const convertedTime = moment.tz(timeZone).format('YYYY-MM-DDTHH:mm:ss');
    console.log(timeZone.padEnd(20), convertedTime)
}
.as-console-wrapper { max-height: 100% !important; }
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

CodePudding user response:

I don't know anything about your back-end, so I can only speculate, but I believe "MST7" and "AST4" are probably POSIX time zones strings. You can read more about them in the timezone tag wiki, in the section "POSIX style time zones" towards the bottom.

POSIX time zone do not uniquely identify a time zone. They aren't identifiers. They only describe some portion of a time zone's behavior.

"MST7" means only two things:

  • This time zone is labeled "MST"
  • This time zone is 7 hours west of GMT

Note that the offsets of POSIX time zones are inverted from the typical ISO 8601 standard. "MST7" has an offset of UTC-7.

Also, because it doesn't give another abbreviation, it implies that daylight saving time is not applicable. Thus it would be UTC-7 year-round. However, there's no way of knowing if that is the rule that has always applied, or just the one that applies presently. That is the main problem with them - they're only a snapshot of the time zone at some undefined point in time.

Moment-Timezone (and most other modern libraries and platforms) don't use POSIX time zones. They use IANA TZ Database identifiers. I highly suggest you update the back end of your app to use them as well.

If you really must use these POSIX time zone strings, you can refer to a post I made many years ago. (However, that is about how to generate them, not how to parse them.)

And lastly, keep in mind that Moment.js is considered to have reached end-of-life. If you are starting a new project, you should choose something else. See the Moment Project Status page. Thanks.

  • Related