简体   繁体   中英

Moment.js Day Ago

I have a problem. I create chat, I use to this moment js. Variable (this.entry.createdData) has date hours of sent message. I would like to display if caller sent me a message yesterday / day before yesterday or in the format DAY: MONTH. Unfortunately it does not work. When message was posted yesterday at 16.15 and today is 15.15 it shows today's date instead of yesterday. Ideas?

    var mom = moment(this.entry.createdDate),
            now = moment(),
            diffInDays = mom.from(now),
            diffInYears = now.diff(mom, 'years');

    if( diffInYears!== 0 ){
        return mom.format('DD MM YYYY')
    }
    else{
        if( diffInDays === "1 day ago" )
            return 'Yesterday';
        else if( diffInDays === "2 days ago" )
            return 'Day Before Yesterday';
        else 
            return mom.format('DD MM');
    }
}

You have to decide "yesterday" by comparing the time with start of today. If the time is between start of yesterday and start of today, then it is.

Checkout APIs https://momentjs.com/docs/#/manipulating/start-of/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM