如何在 JavaScript 中向 HH:MM:SS 添加分钟数?
How to add minutes to HH:MM:SS in JavaScript?
我想将分钟(整数类型)添加到 HH:MM:SS(字符串类型)。
示例:
let min = 125;
let time = "10:00:00";
结果 = "12:05:00"
首先你必须解析文本,然后创建一个日期对象,然后加上 125 分钟(以毫秒为单位)最后但并非最不重要的是你可以格式化创建的日期:
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
我认为此 post 中的所有其他答案(没有日期对象)都不正确。
您可以使用 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
参见:codepen
你可以试试这个
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(":");
}
这是一个快速函数,可以将 添加分钟 到时间字符串 HH:MM:SS。
不影响秒,只是操纵分钟和小时。
可以改进,但只是一个快速的解决方案。
下面有几个测试示例。
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'
一种策略是将值转换为通用组件(如秒),添加值,然后将格式设置为 H:mm:ss。通用函数通常比 ad hoc 函数具有更广泛的适用性,因此如果您将分钟作为数字,最好将其重构为调用中的字符串,例如
/** 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));
上面的 addTimes 函数不处理负值。如果你想这样做,处理标志还有一些工作,特别是输出:
/** 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));
注意ECMAScript中没有整数类型,只有number。
我想将分钟(整数类型)添加到 HH:MM:SS(字符串类型)。
示例:
let min = 125;
let time = "10:00:00";
结果 = "12:05:00"
首先你必须解析文本,然后创建一个日期对象,然后加上 125 分钟(以毫秒为单位)最后但并非最不重要的是你可以格式化创建的日期:
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
我认为此 post 中的所有其他答案(没有日期对象)都不正确。
您可以使用 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
参见:codepen
你可以试试这个
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(":");
}
这是一个快速函数,可以将 添加分钟 到时间字符串 HH:MM:SS。 不影响秒,只是操纵分钟和小时。 可以改进,但只是一个快速的解决方案。 下面有几个测试示例。
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'
一种策略是将值转换为通用组件(如秒),添加值,然后将格式设置为 H:mm:ss。通用函数通常比 ad hoc 函数具有更广泛的适用性,因此如果您将分钟作为数字,最好将其重构为调用中的字符串,例如
/** 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));
上面的 addTimes 函数不处理负值。如果你想这样做,处理标志还有一些工作,特别是输出:
/** 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));
注意ECMAScript中没有整数类型,只有number。