Today, yesterday… how to format the date display so it has the corresponding day label in Javascript

Veloso
2 min readJan 16, 2023

One day you were selected for a task where the request was, I need to display if the date that was returned corresponds to today, or yesterday and display the corresponding day label.

Today we are going to talk about the Javascript library called date-fns, which facilitates the development of data formats.

To learn more about the power this library gives you, visit the official documentation: https://date-fns.org/docs/Getting-Started

But straight to what our task asks:

You are in a front-end project, after installing the library, let’s go to the necessary import:

import { format, parseISO, isToday, isYesterday } from ‘date-fns’;

If you are receiving data as a String, ParseISO will parse it to an instance of Data

So let’s assign that date to a constant:

const date = 2023–01–16T02:08:55.000Z

Now let’s create a function that, when receiving a date, will do the formatting:

const formatDate = (date) => {
const parsedDate = parseISO(date);

if (isToday(parsedDate)) {
return `today ${format(parsedDate, 'kk:mm')}`
}

if (isYesterday(parsedDate)) {
return `yesterday ${format(parsedDate, 'kk:mm')}`
}

return format(parsedDate, 'dd/MM/yyyy');
};

In this function, if the past date is the current date, the value returned will be Today + the time returned

Today 08:55

If the date is the previous day’s date, the returned value will be

Yesterday 08:55

Otherwise, it will return the date in the format presented:

01/16/2023

These and other good formattings the library gives you in a direct and simplified way, see also in the official documentation how TimeZones, Locale, and other formatting apply :)

--

--

Veloso

Little Tom's father, musician, and lover of running as a sport, I've dedicated 10 years of my life to software engineering using Python and Javascript.