Wandi
Wandi

Reputation: 57

ReactJS: convert date to a hours/minutes ago or day/hours ago

someone can help me, i have a date of coment with result:

June 10, 2022, 3:29 PM

i want to convert if the date coment same with the day now, value:

14 hours, 27 minutes ago

when the date coment not same with day now:

2 day, 15 hours ago

Upvotes: 3

Views: 1901

Answers (3)

Abhishek Shukla
Abhishek Shukla

Reputation: 666

Check out date-fns library. It is lightweight.

https://date-fns.org/docs/Getting-Started

some examples

import { format, formatDistance, formatRelative, subDays } from 'date-fns'

format(new Date(), "'Today is a' eeee")
//=> "Today is a Thursday"

formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"

formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."

Upvotes: 2

Hitend
Hitend

Reputation: 1

Checkout for moment library to convert the date to the hours/minutes ago or day/hours ago.

Upvotes: 0

Naren Murali
Naren Murali

Reputation: 57696

Use Moment.js fromNow() this will produce your desired result!

moment([2007, 0, 29]).fromNow();     // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years

Upvotes: 2

Related Questions