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

236
Views
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 answers
Answer question

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 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!