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

169
Views
Convert string to time and add 2 hours in JS

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

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!