Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to parse a time string using Moment.js but ignore timezone info?

Tags:

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.

Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.

For example, if I am in EDT timezone:

var x = moment( "2012-12-31T00:00:00+0000" );

will give me: "2012-12-30T19:00:00-5000"

I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).

like image 215
Eric B. Avatar asked Aug 21 '14 14:08

Eric B.


People also ask

How do I remove timezone from moment date?

momentDate. format('YYYY-MM-DDTHH:mm:ss') + '00:00'; This would remove the timezone and then append the '00:00' part back in.

Why you shouldnt use moment JS?

However, Moment. js has too many drawbacks compared to modern date and time libraries. Its API is not immutable, it is large and it doesn't support tree shaking. Even the Moment team discourages to use their library in new projects.

What can I use instead of moment in Javascript?

There are several libraries out there that can potentially replace Moment in your app. The creators of Moment recommend looking into Luxon, Day. js, date-fns, js-Joda, or even replacing Moment with native JS.


2 Answers

I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.

Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:

var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format();   // "2012-12-31T00:00:00+00:00"

You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.

like image 91
Matt Johnson-Pint Avatar answered Oct 03 '22 06:10

Matt Johnson-Pint


I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.

moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()

This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.

like image 45
Mark Avatar answered Oct 03 '22 06:10

Mark