I would like to show a UNIX timestamp into last seen status same as what WhatsApp does in javascript. I am using moment.js
and as far as I know, we can format the date or can use .fromNow()
which gives a relative date but not what I am looking for.
For example, Lets the Unix timestamp: 1606908420
If I use moment.unix(1606908420).formNow()
the result will be few seconds ago
or something similar
But what I am looking for is, it should show Today 11:30 am
.
Likewise
For a date of yesterday, it should show: Yesterday 11:30 am
For a date of day before yesterday, it should show: Mon 11:30 am
Any date of last week or earlier, it should show 25-11-2020
Can anyone please help me how can I achieve this?
using toDate() method
{new Date(timestamp?.toDate()).toUTCString()}
Wed, 2 Dec 2020 12:00:00 GMT
using moment method
{moment.unix(order.data.created).format("MMMM Do YYYY, h:mma")}
I highly recommend the second one moment for you. learn more from moment docs
Convert Moment Date to looks like In Whatsapp
//utility function to convert your date to looks like in whatsapp
const dateFormatter = (date) => {
//here we were subtracting our date from current time which will be in milliseconds
const dateDifferenceInTime =
new Date().getTime() - new Date(date.toDate()).getTime();
// conerting milli seconds to days
// (1000 milliseconds * (60 seconds * 60 minutes) * 24 hours)
const dateDifferenceInDays =
dateDifferenceInTime / (1000 * 60 * 60 * 24);
//After returning in particular formats as of our convinent
if (dateDifferenceInDays < 1) {
return moment(date.toDate()).format("LT");// 10:04 am
} else if (dateDifferenceInDays < 2) {
return "Yesterday"; // just YesterDay
} else if (dateDifferenceInDays <= 7) {
return moment(date.toDate()).format("dddd");//like monday , tuesday , wednesday ....
} else {
return moment(date.toDate()).format("l");// if it was more than a week before it will returns as like 05/23/2022
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.