Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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 ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!