Home > front end >  Convert string to time and add 2 hours in JS
Convert string to time and add 2 hours in JS

Time:09-17

i get this time from an external JSON :

"time":"19:45"
I need to add 2 hours from this string.
Is it possible in JS? Thanks

CodePudding user response:

Try this

let myTime = '19:45'

function getTime(time, addHour) {
  let [h, m] = time.split(':');
  let date = new Date();
   date.setHours(h, m, 0)
   date.toString();
  let res = `${date.getHours() addHour}:${date.getMinutes()}`
  return res
}
 
console.log(getTime( myTime, 2 ))

CodePudding user response:

uses String.split to get hourNum and minuteNum, then construct one Date object and uses setTime to add two hours.

function addHours(text, hours=2) {
  const [hourNum, minNum] = text.split(':')
  const time = new Date(0, 0, 0, hourNum, minNum)
  time.setTime(time.getTime()   (hours * 60 * 60 * 1000))
  return `${time.getHours()}:${time.getMinutes()}`
}

console.log(addHours('19:45', 2))
console.log(addHours('23:45', 2))

CodePudding user response:

A Date object isn't necessary to do time mathematics, it just means taking account of minutes and seconds (60) and maybe days (24).

E.g.

// Add time to a timestamp, both in in HH:mm format
// If respectDay is true, hours are % 24
function addTime(start, increment, respectDay = false) {
  let pad = n => ('0'   n).slice(-2);
  let timeToMins = time => time.split(':').reduce((h, m) => h*60   m*1);
  let minsToTime = (mins, respectDay = false) => `${pad((mins / 60 | 0) % (respectDay? 24 : Number.POSITIVE_INFINITY))}:${pad(mins%60)}`;
  return minsToTime(timeToMins(start)   timeToMins(increment), respectDay);
}

let time = "19:45";
console.log(addTime(time, '8:23'));       // Total time  : 28:08
console.log(addTime(time, '8:23', true)); // As day time : 04:08

  • Related