Moment.js React Hook


July 2021

Moment.js is an absolute must-have in any application that handles time.

One of my favorite features is the ability to convert a timestamp into a human-friendly format with a simple .calendar() suffix. For example:

moment().calendar();
// Today at 2:41 pm
moment().subtract(1, "days").calendar();
// Yesterday at 2:41 pm
moment().subtract(3, "days").calendar();
// Last Monday at 2:41 pm

However, the .calendar() formatting option falls somewhat short when handling older events:

moment().subtract(10, "days").calendar();
// 07/12/2021

What if I wanted to display the time next to the date? To fix that limitation, I wrote a simple and handy hook that uses .calendar() only for events happened in the last 24 hours, while switching to a more specific .format("MMMM Do, h:mm a") for older events.

Note: the syntax below uses Unix timestamps (in seconds) as input – for example "1626980847" for July 22 2021 7:07:27 PM GMT – but of course it can be easily modified to work with any other format.

export default timestamp => {
// First, let's get the timestamp for yesterday at midnight, local time
let yesterday = moment().local().add(-1, "days").startOf("day").unix();
// If our timestamp is from today or yesterday, we use .calendar() to get a friendly output like "Today at 10:33 am"
if (timestamp >= yesterday) {
return moment.unix(timestamp).local().calendar();
// Otherwise, let's use a specific formatting option to get a nice and complete output like "July 20th, 11:40 pm"
} else {
return moment.unix(timestamp).local().format("MMMM Do, h:mm a");
}
};

That's all folks!

© 2023 Stefano Picker