0

I made a countdown clock which shows how many years, months, days, hours, minutes and seconds left until certain moment in time.

I just have a small issue solution to which should be obvious enough but I just can't figure it out for the life of me. How can I format data that comes out of timeBetween.hours() and timeBetween.seconds()? I need them to always be of 2-digit format but by default if a number is less than 10 it's not padded with another zero.

format() function doesn't work with duration. I found a workaround by formatting moment(timebetween)._data but then I have a month off since it becomes index based.

Here's the code:

const Clock = () => {
const [clock, setClock] = useState(moment());

const theEnd = moment('2050-01-01 00:00:00');
const timeBetween = moment.duration(theEnd.diff(clock));

useEffect(() => { setInterval(() => setClock(moment()), 1000)}, []);

return (
    <div className="clock-container">
        <p className='time'>{`${timeBetween.years()} years, ${timeBetween.months()} months, ${timeBetween.days()} days`}</p>
        <p className='time'>{`${timeBetween.hours()} hours : ${timeBetween.minutes()} minutes : ${timeBetween.seconds()} seconds`}</p>
    </div>
);
};
export default Clock;
magrega
  • 37
  • 7
  • Have you tried with this https://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date – Santiago Casas Rey Apr 19 '23 at 13:41
  • I keep thinking that I can do this using momentjs functionality. It has a great format() function which allows for a very flexible data formatting but I just don't get how to apply it to durations but thanks I'll look into it – magrega Apr 19 '23 at 13:45

1 Answers1

0

I padded it like this. The simplicity is overwhelming.

const zeroPad = (num: number) => String(num).padStart(2, '0');

<div className="clock-container">
            <p className='time'>{`${timeBetween.years()} years, ${timeBetween.months()} months, ${timeBetween.days()} days`}</p>
            <p className='time'>{`${zeroPad(timeBetween.hours())} hours : ${zeroPad(timeBetween.minutes())} minutes : ${zeroPad(timeBetween.seconds())} seconds`}</p>
        </div>
magrega
  • 37
  • 7