Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda