moment / luxon

⏱ A library for working with dates and times in JS
https://moment.github.io/luxon
MIT License
15.12k stars 728 forks source link

luxon toRelative() returning different values while migrating from moment fromNow() #1492

Closed Gokulkannan08 closed 11 months ago

Gokulkannan08 commented 11 months ago

Describe the bug Migrating from moment to luxon: In my case moment.fromNow() and luxon.DateTime.toRelative() return different value

To Reproduce

DateTime.fromISO(new Date('2023-08-07T12:54:56.886Z').toISOString()).toRelative()

returns 16 days ago

Actual vs Expected behavior As expected should be 17 days ago

moment('2023-08-07T12:54:56.886Z').fromNow()

returns 17 days ago

icambron commented 11 months ago

You'll need to tell us what time it was when you ran this, and what time zone that was in.

Gokulkannan08 commented 11 months ago

Checked round 10.30 am (IST) in the morning and periodically after that timezone - "Asia/calcutta"

diesieben07 commented 11 months ago

I cannot reproduce this with the following code:

const dummyNow = DateTime.fromISO('2023-08-25T10:30', {zone: 'Asia/Calcutta'}).toMillis();
Settings.now = () => dummyNow;
Settings.defaultZone = 'Asia/Calcutta';
Settings.defaultLocale = 'en-US';
console.log(DateTime.fromISO(new Date('2023-08-07T12:54:56.886Z').toISOString()).toRelative());

This produces "17 days ago" for me, in Node.JS 18, Chrome and Firefox.

Please provide more details for how to reproduce this issue.

Gokulkannan08 commented 11 months ago

I have attached the screenshot below.

Luxon Screenshot from 2023-08-27 11-33-52

Moment Screenshot from 2023-08-27 11-33-41

diesieben07 commented 11 months ago

Okay, so the date you're using is 2023-08-07T18:24:56 in your time zone. Since the current time in your time zone is 2023-08-27T11:33:00, 19 days and a few hours have passed. As such the report "19 days ago" is entirely accurate.

Moment.js does some funky rounding when you call fromNow instead of giving you an accurate report. In Luxon you can use the padding option of toRelative to round up to e.g. the nearest day.

Gokulkannan08 commented 11 months ago

@diesieben07 How to round up with the nearest day using padding in toRelative()?

diesieben07 commented 11 months ago
const padding = Duration.fromObject({days: 1}).toMillis() / 2;
const relative = DateTime.fromISO('2023-08-07T12:54:56.886Z').toRelative({ padding });