How to format date using date-fns library in JavaScript?
The date utility or library date-fns
provides simple and easy ways to format JavaScript dates in a browser and Node.js.
In our use case, we had the following requirements:
Published today: Just hour HH:MM
Published this week: Weekday and timestamp HHMM
Older than 1 week: DD/MM
Published this week: Weekday and timestamp HHMM
Older than 1 week: DD/MM
If the date is today, we just needed to print HH:MM of that date. If the date is yesterday or within this week we had to print weekday namea and hour and minute like this: HH:MM
If the date is older than one week, we had to print DD/MM (only and date and month)
By using date-fns
utility, we could very easily achieve this. Following is the react code that we wrote to get this done:
import formatRelative from 'date-fns/formatRelative'; import nb from 'date-fns/locale/nb'; // We had to use Norwegian locale const formatRelativeLocale = { lastWeek: 'eeee HH:mm', yesterday: 'eeee HH:mm', today: 'HH:mm', other: 'dd.MM.yyyy', }; const locale = { ...nb, formatRelative: (token) => formatRelativeLocale[token], }; return ( <div className="App"> {formatRelative(new Date(2014, 1, 11), new Date(), { locale })} // 11.01.2014 </div> );