Date-fns—omit year if it's current year

Viewed 1303

Using the format function of date-fns, is it possible to omit the year if it is the current year? Is there some format string to enable this?

import { format } from 'date-fns'

const date = new Date('July 4, 2021')

// current year is 2021

format(date, 'format string')
// should output "July 4"

format(date, 'format string')
// should output "July 4, 2020"

If there's another date-fns function that does this aside from format, that's also fine. I'm assuming though that any such solution will likely use the format function since this is, well, formatting the date.

Alternative solutions

I know it's currently possible to use an if statement to do this manually.

const date = new Date('July 4, 2021')
if (date.getFullYear() === (new Date()).getFullYear()) {
    format(date, 'MMM d')
} else {
    format(date, 'MMM d, YYY')
}

While this works, I'm more curious if there's a way to format this natively with date-fns.

0 Answers
Related