Daniyar Changylov
Daniyar Changylov

Reputation: 568

what's wrong with format moment js?

we have 2 isoString dates:

startedAt: '2023-10-18T14:03:36.150Z',
closedAt: '2023-10-18T18:13:33.150Z'

When I'm taking duration differences it's working good:

const duration = moment.duration(moment(closedAt).diff(startedAt));
const days = duration.days(); // 0
const hours = duration.hours(); // 4
const minutes = duration.minutes(); // 9
const seconds = duration.seconds(); // 57

But, when I'm formating it shows:

const start = moment(startedAt).format('DD, dddd, hh:mm:ss');
const end = moment(closedAt).format('DD, dddd, hh:mm:ss');
// start: 18, wednesday, 08:03:36 (+6GMT)
// end: 19, thursday, 12:13:33 (+6GMT)

why, day is 19?

Upvotes: -1

Views: 88

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074198

why, day is 19?

Because the 18th at 18:13:33 UTC is the 19th at 00:13:33 in your local timezone (GMT+06:00) (which is displayed as 12:13:33 because the hh format specifier is for the 12-hour clock). Those strings represent moments in time UTC (the Z at the end indicates that), so that's how Moment parses them. But by default, Moment formats in local time. So you're seeing a difference based on your timezone. You can use the utc method to tell Moment to format using UTC instead:

moment(closedAt).utc().format('DD, dddd, hh:mm:ss');
// −−−−−−−−−−−−−−^^^^^^

Beware that hh is the 12-hour clock, though. Use HH if you want the 24-hour clock.

Upvotes: 3

Related Questions