简体   繁体   中英

How to add minutes to HH:MM:SS in JavaScript?

I want to add Minutes (typeof Integer) to HH:MM:SS (typeof String).

Example:

let min = 125;
let time = "10:00:00";

Result = "12:05:00"

You can try this

 let min = 125; let time = "10:00:00"; console.log(addtime(time,min)); function addtime(time,hour){ let times=time.split(":"); //clear here more than 24 hours min=min%(24*60); times[0]=(parseInt(times[0]))+parseInt(min/60); times[1]=parseInt(times[1])+min%60; //here control if hour and minutes reach max if(times[1]>=60) { times[1]=0;times[0]++}; times[0]>=24? times[0]-=24:null; //here control if less than 10 then put 0 frond them times[0]<10? times[0]= "0" + times[0]: null; times[1]<10? times[1]= "0" + times[1]: null; return times.join(":"); }

Here is a quick function to just add minutes to a time string HH:MM:SS . Does not affect the seconds and just manipulates the minutes and hours. Can be improved, but is only a quick solution. Hope it helps. With few test examples below.

 function timeAddMinutes(time, min) { var t = time.split(":"), // convert to array [hh, mm, ss] h = Number(t[0]), // get hours m = Number(t[1]); // get minutes m+= min % 60; // increment minutes h+= Math.floor(min/60); // increment hours if (m >= 60) { h++; m-=60 } // if resulting minues > 60 then increment hours and balance as minutes return (h+"").padStart(2,"0") +":" //create string padded with zeros for HH and MM +(m+"").padStart(2,"0") +":" +t[2]; // original seconds unchanged } // ======= example tests ============= console.log(timeAddMinutes('10:00:00', 125)); // '12:05:00' console.log(timeAddMinutes('10:47:00', 4*60+15)); // '15:02:00' console.log(timeAddMinutes('10:00:00', 0)); // '10:00:00' console.log(timeAddMinutes('10:00:00', 60+17)); // '11:17:00' console.log(timeAddMinutes('00:30:00', 30)); // '01:00:00' console.log(timeAddMinutes('05:45:00', 45)); // '06:30:00' console.log(timeAddMinutes('10:00:00', 60*100+5)); // '110:05:00'

One strategy is to convert the values to a common component like seconds, add the values, then format as H:mm:ss. General functions usually have wider applicability than ad hoc ones, so given that you have minutes as a number it would be better to refactor it to a string in the call, eg

 /** Add times, only deals with positive values ** @param {string} t0: time in h[:mm[:ss]] format ** @param {string} t1: time in same format as t0 ** @returns {string} summ of t0 and t1 in h:mm:ss format **/ function addTimes(t0, t1) { return secsToTime(timeToSecs(t0) + timeToSecs(t1)); } // Convert time in H[:mm[:ss]] format to seconds function timeToSecs(time) { let [h, m, s] = time.split(':'); return h*3600 + (m|0)*60 + (s|0)*1; } // Convert seconds to time in H:mm:ss format function secsToTime(seconds) { let z = n => (n<10? '0': '') + n; return (seconds / 3600 | 0) + ':' + z((seconds % 3600) / 60 | 0) + ':' + z(seconds % 60); } let min = 125; let time = "10:00:00"; console.log(addTimes('0:'+ min, time)); // or console.log(addTimes(secsToTime(min * 60), time));

The above addTimes function doesn't handle negative values. If you wan to do that, there's a little more work to handle the sign, particularly for output:

 /** Add times ** @param {string} t0: time in [-]h[:mm[:ss]] format ** @param {string} t1: time in same format as t0 ** @returns {string} summ of t0 and t1 in h:mm:ss format **/ function addTimes(t0, t1) { return secsToTime(timeToSecs(t0) + timeToSecs(t1)); } // Convert time in H[:mm[:ss]] format to seconds function timeToSecs(time) { let sign = /^-/.test(time); let [h, m, s] = time.match(/\d+/g); return (sign? -1: 1) * (h*3600 + (m|0)*60 + (s|0)*1); } // Convert seconds to time in H:mm:ss format function secsToTime(seconds) { let sign = seconds < 0? '-':''; seconds = Math.abs(seconds); let z = n => (n<10?'0':'') + n; return sign + (seconds / 3600 | 0) + ':' + z((seconds%3600) / 60 | 0) + ':' + z(seconds%60); } let min = -125; let time = "10:00:00"; // Convert min to a timestamp in the call console.log(addTimes(secsToTime(min * 60), time));

Note that there is no integer type in ECMAScript, there is only number .

First you have to parse the text, then create a date object, then add 125 minutes (in millis) and last but not least you can format the created date:

 let min = 125; let [hh, mm, ss] = "10:00:00".split(':').map(s=>parseInt(s, 10)); const d = new Date(); d.setHours(hh); d.setMinutes(mm); d.setSeconds(ss); const result = new Date(d.getTime() + 125 * 60 * 1000); console.info(result); // result is the date with the correct time // formatting the output: const dateTimeFormat = new Intl.DateTimeFormat('de', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', }); const [,,,,,,{value:hour},,{value: minute},,{value: second}] = dateTimeFormat.formatToParts(result); console.info(`${hour}:${minute}:${second}`);

--> 12:05:00

I think that all other answers in this post (without date object) are incorrect.

You can make a doublecheck with moment.js:

let now = new Date();
var date = moment(new Date(), "hh:mm:ss");
console.info(date.format('LTS')); // -> 7:50:37 AM

date = date.add(262080 , 'minutes');
console.info(date.format('LTS')); // -> 6:50:37 AM

See: codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM