Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading