Get the distance between the given date and now in words using date-fns
Gustavo
Posted on April 7, 2023
- import the formatDistanceToNow function from date-fns:
import { formatDistanceToNow } from 'date-fns'
- format the date to now:
const date = new Date('2020-01-01T12:00:00Z')
console.log(formatDistanceToNow(date, { addSuffix: true }))
- as you've seen, we can also pass the second parameter as an object to specify the options, such as adding the suffix.
- you can see all the available options for
formatDistanceToNow
here
Using a different language
- we need to import the language from date-fns, for example, portuguese from Brazil:
import ptBR from 'date-fns/locale/pt-BR'
- then use the second parameter to specify the locale
import { formatDistanceToNow } from 'date-fns'
import ptBR from 'date-fns/locale/pt-BR'
const date = new Date('2020-01-01T12:00:00Z')
console.log(
formatDistanceToNow(date, {
addSufix: true,
locale: ptBR,
})
)
Reference
date-fns
docs- Cover image from Roman Bozhko on Unsplash
đź’– đź’Ş đź™… đźš©
Gustavo
Posted on April 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.