Search code examples
javascriptreactjsmomentjsnative

Moment.Js calculate difference datetime and show result


Library moments.js included. I have a variable "lastMessage.created_at" If it today's date to display then time in the format "h:mm a" if it was yesterday, display "Yesterday" or before that "D.M.Y", how do I do this ?


Solution

  • You could create a function to format input dates, these can be strings (in supported formats), Dates or moment objects.

    We'll then output a different format based on whether the date is the same or after the start of today, the start of yesterday, or before that.

    function formatDisplayDate(input) {
        const dt = moment(input);
    
        const startOfToday = moment().startOf('day');
        const startOfYesterday = moment().startOf('day').subtract(1, 'day');
        
        if (dt.isSameOrAfter(startOfToday)) {
            return dt.format('h:mm a');
        } else if (dt.isSameOrAfter(startOfYesterday)) {
            return 'Yesterday';
        } else {
            // Before yesterday
            return dt.format('D.M.Y');
        }
    }
    
    const inputs = [ new Date().toLocaleString('sv'), new Date(Date.now() - 86400000).toLocaleString('sv'), new Date(Date.now() - 4*86400000).toLocaleString('sv') ];
    for (let input of inputs) {
        console.log(`Input: ${input}, output: ${formatDisplayDate(input)}`);
    }
            
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script>