- import the formatDistanceToNow function from date-fns:
import { formatDistanceToNow } from 'date-fns'
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
Top comments (0)