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

237
Vistas
Add time to current date in javascript or type script

i am trying to add a time to current date.

example:

i have this time : 05:17 am

i want to add this time current date by replace current time by this time.

if current date and time is : 10-09-2021 11:30 am

i want to add current date and replace time by my specific time => output for example above: 10-09-2021 05:17 am

i am trying:

var time = this.timeInput;
new Date().getTime() + convertTimeToInt(time);

// in this case we add current time to my input time, i don't want this.

convertTimeToInt() is a method that convert time to int.

Any idea?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This will do

let time = '05:17 pm';
let splittedTime = time.split(' ');
let [hours, minutes] = splittedTime[0].split(':');
let isAm = splittedTime[1] === 'am'; // in europe we don't use am, the hours goes from 0 to 24

var date = new Date(); // now
console.log('before ' + date); 

let hourToAdd = 0;
if(+hours === 12) {
    if(isAm) {
        hourToAdd = - 12; // at midnight we dont add +12 nor +0, we want 12am to be 0 hours
    } else {
        hourToAdd = 0;
    }
} else {
    hourToAdd = isAm ? 0 : 12;
}

// use setHours to set time
date.setHours(+hours + hourToAdd, +minutes, 0, 0); 
console.log('after ' + date);  

Output:

let time = '12:17 pm';
[LOG]: "before Fri Sep 10 2021 14:37:07 GMT+0200
[LOG]: "after Fri Sep 10 2021 12:17:00 GMT+0200

let time = '12:17 am';
[LOG]: "before Fri Sep 10 2021 14:37:27 GMT+0200
[LOG]: "after Fri Sep 10 2021 00:17:00 GMT+0200

let time = '05:17 am';
[LOG]: "before Fri Sep 10 2021 14:37:45 GMT+0200
[LOG]: "after Fri Sep 10 2021 05:17:00 GMT+0200

let time = '05:17 pm';
[LOG]: "before Fri Sep 10 2021 14:38:21 GMT+0200
[LOG]: "after Fri Sep 10 2021 17:17:00 GMT+0200

UPDATE: without am/pm, you can use

let time = '05:17';
let [hours, minutes] = time.split(':');
var date = new Date(); // now
console.log('before ' + date); 
date.setHours(+hours, +minutes, 0, 0); // set hours/minute
console.log('after ' + date); 

Output:

[LOG]: "before Fri Sep 10 2021 11:03:07 GMT+0200 
[LOG]: "after Fri Sep 10 2021 05:17:00 GMT+0200 
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