Home > other >  Add time to current date in javascript or type script
Add time to current date in javascript or type script

Time:09-17

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?

CodePudding user response:

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 
  • Related