Marek
Marek

Reputation: 4081

Ignoring timezone when creating moment date from string containing timezone

In my Angular project I am creating a moment object by passing a date string, which contain timezone information.

I would like to get rid of this information, and make sure that this date will always be same day, regardless of a timezone that I am currently in.

I could do this by splitting the date string like below:

let dateString = '2020-12-21T15:00:00+05:00'

let date = moment(dateString.split('T')[0]) 

But it is probably not the right approach to do this. Will the below code let me archive same thing?

let date = moment(dateString, YYYY-MM-DD) 

In both cases, when I afterwards display the date, I would like to see same result: 2020-12-21 (regardless of the timezone that I am currently in):

console.log(date.format(YYYY-MM-DD)) // should always log 2020-12-21

Also, I found other posts that I should use utc method, but it is not working for me. I just want to totally get rid of timezone information, and create a moment in my timezone, because I am interested only in the date and not time

Upvotes: 0

Views: 253

Answers (1)

Owl
Owl

Reputation: 6853

moment.utc(dateString); will converts the time to UTC time (Moment<2020-12-21T18:00:00Z>)

Using moment(date, format) seems to be the correct approach

// fyi, my timezone offset is +7
console.log(moment("2020-12-21T023:00:00+05:00", "YYYY-MM-DD"));
// Moment<2020-12-21T00:00:00+07:00>

It's also slightly faster than the .split

console.time("format");
moment("2020-12-21T023:00:00+05:00", "YYYY-MM-DD");
console.timeEnd("format");

console.time("split");
moment("2020-12-21T023:00:00+05:00".split("T")[0]);
console.timeEnd("split");

/*
format: 0.475ms
split: 0.662ms
*/

Use moment.parseZone instead

let date = moment.parseZone(dateString).format("YYYY-MM-DD");

which is equivalent to

let date = moment(dateString).utcOffset(dateString).format("YYYY-MM-DD");

From moment docs:

Moment's string parsing functions like moment(string) and moment.utc(string) accept offset information if provided, but convert the resulting Moment object to local or UTC time. In contrast, moment.parseZone() parses the string but keeps the resulting Moment object in a fixed-offset timezone with the provided offset in the string.

But i think moment(dateString.split('T')[0]) is also a right way to do this. It's also faster

const dateString = "2020-12-21T23:00:00+05:00";

console.time("parzeZone");
moment.parseZone(dateString);
console.timeEnd("parzeZone");

console.time("moment");
moment(dateString.split("T")[0]);
console.timeEnd("moment");

/*
parzeZone: 4.180ms
moment: 0.356ms
*/

Upvotes: 1

Related Questions