DEV Community

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

Posted on

3

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay