DEV Community

Cover image for Get the distance between the given date and now in words using date-fns
Gustavo
Gustavo

Posted on

Get the distance between the given date and now in words using date-fns

  • import the formatDistanceToNow function from date-fns:
import { formatDistanceToNow } from 'date-fns'
Enter fullscreen mode Exit fullscreen mode
  • format the date to now:
const date = new Date('2020-01-01T12:00:00Z')
console.log(formatDistanceToNow(date, { addSuffix: true }))
Enter fullscreen mode Exit fullscreen mode
  • 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'
Enter fullscreen mode Exit fullscreen mode
  • 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,
  })
)
Enter fullscreen mode Exit fullscreen mode

Reference

Top comments (0)