Sredny M Casanova
Sredny M Casanova

Reputation: 5053

format moment JS date substracts one day

I am currently using moment.js and I am facing a problem to format a date to DD MMM as it's giving me one day less that the original date. I am making the transformation with the next line:

moment(date).format('DD MMM')

As an example, date is 2019-09-12T00:00:00Z and for this date, moment is giving me: 11 sept

Then, why 11 and not 12? is this related with the fact that the hour is 00:00:00Z ? In that case, how should be threated?

Thanks in advance

Upvotes: 1

Views: 1183

Answers (1)

Phoenix
Phoenix

Reputation: 129

Yes, this is almost surely because it is formatting the date in your current time zone, but the original time is expressed in UTC — the Z at the end means "zero time zone offset from UTC". For reference, a date with a time zone would, instead of Z have something like -06:00 at the end.

I believe you can solve your issue by using the moment.utc method, which causes prints of that date to be printed in UTC rather than your local timezone.

Compare printing the date (with timezone included) without the .utc: (my timezone is UTC -6)

console.log(moment('2019-09-12T00:00:00Z').format('DD MMM Z'));
=> 11 Sep -06:00

vs with .utc:

console.log(moment.utc('2019-09-12T00:00:00Z').format('DD MMM Z'));
=> 12 Sep +00:00

Upvotes: 2

Related Questions