Home > Software design >  moment - diff between two dates not quite right
moment - diff between two dates not quite right

Time:11-21

I'm trying to code a countdown timer to Christmas day. Below is what I have. However, days is coming out as 3 for some reason. If I set the then date up 22nd December - it will calculate it right but any dates after that it seems to start from 1 - meaning if I set it to 2022-12-23 00:00:00, days is outputting 1, 2022-12-24 00:00:00 will give me 2 days to the countdown. I'm a bit confused what is happening here...

    const [days, setDays] = useState(0);
    const [hours, setHours] = useState(0);
    const [minutes, setMinutes] = useState(0);
    const [seconds, setSeconds] = useState(0);
    

    useEffect(() => {
        setInterval(() => {
            const now = moment();
            const then = moment("2022-12-23 00:00:00", "YYYY-MM-DD hh:mm:ss");
            const countdown = moment(then - now);
            setDays(countdown.format("D"));
            setHours(countdown.format("HH"));
            setMinutes(countdown.format("mm"));
            setSeconds(countdown.format("ss"));
        }, 1000);
    }, []);

CodePudding user response:

I'm not using moment, I prefer dayjs but it seems like your issue is that you are trying to get the difference between two dates here

const countdown = moment(then - now);

That returns something weird.

I'd use

const diff = then.diff(now, 'seconds');
const days = diff / 60 / 60 / 24;
// ... and so on

// or

const days = then.diff(now, 'days');
// ... and so on

and I'd calculate the difference in days, hours, minutes and seconds with that. Maybe there's a moment method that does all of that for you in one function call but I didn't find it, although I didn't look very hard.

More about diff here.

CodePudding user response:

You can use moment.diff to get the difference between two dates.

We can use this to create a duration object and use this to get the number of days, hours minutes etc until the date.

function dispayTimeUntilDate(date, tag) {
    const duration = moment.duration(date.diff(moment()));
    const [days, hours, minutes, seconds ] = [ Math.floor(duration.asDays()), duration.hours(), duration.minutes(), duration.seconds()];
    const fmt = `It is ${days} days, ${hours} hours, ${minutes} minutes and ${seconds} seconds until ${tag}`;
    document.getElementById('output').innerHTML = fmt;
}

const christmas = moment([2022, 11, 25]);
setInterval(() => dispayTimeUntilDate(christmas, 'Christmas'), 1);
<p id="output"></p>

<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

  • Related