【问题标题】:How to add minutes to HH:MM:SS in JavaScript?如何在 JavaScript 中向 HH:MM:SS 添加分钟数?
【发布时间】:2020-09-10 15:39:41
【问题描述】:

我想将 Minutes (typeof Integer) 添加到 HH:MM:SS (typeof String)。

例子:

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

结果 = "12:05:00"

【问题讨论】:

  • 请发布您尝试完成此操作的代码。
  • 对于 JavaScript 中与日期时间相关的任何事情,我总是使用 momentjs,虽然它易于使用和理解,但它总是可以轻松完成工作
  • 您想获得时间信息作为结果还是想获得以小时为单位的持续时间。分秒?
  • @Marc 在 HH:MM:SS
  • 每个答案都能解决我的疑问。谢谢大家

标签: javascript string date time datetime-conversion


【解决方案1】:

你可以试试这个

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(":");
}

【讨论】:

  • 对于这个输入 "23:00:00" 你会得到 "25:05:00"
  • 对不起。试试这个:让 min = 60 * 48 + 10;
  • 冬至夏的跳跃?恐怕非日期解决方案并不可靠。
  • 但是他没有白天的时间。只有一个小时。所以这里不能有夏令时。如果他有时间,也可以有一天的信息。他只是试图增加小时。如果他只是尝试在字符串中添加小时,那么夏令时也会给他错误的结果,时区也会给他错误的结果。
  • @Marc — OP 是关于在时间上增加分钟。没有日期的概念。夏令时问题是特定日期的本地问题,可以通过将时间添加到 UTC,然后转换为本地来解决。
【解决方案2】:

一种策略是将值转换为通用组件(如秒),添加值,然后格式化为 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

【讨论】:

  • 如果在“10:00:00”(182 天)上加上 262080 分钟会得到什么?
  • @Marc — 你会得到(262080 / 60) + 10 小时或 4378:00:00。
  • 如果您想获得持续时间,您的代码是正确的。像这样的东西。 4378小时。据我了解,Shubham 希望获得时间作为结果。 Shubham 应该根据他的意图发表评论。
【解决方案3】:

这是一个快速函数,只需 添加分钟 到时间字符串 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'

【讨论】:

  • 这不是我认为的时间:'110:05:00'。它更像是 110h 5m 的持续时间。
  • @Marc。真的。我只是将其添加为超过 23 小时的示例。如果他愿意,他可以将其转换为天数。
  • 因为我只想从电影长度中获取特定电影节目的结束时间。所以这个答案也解决了我的疑问。谢谢
【解决方案4】:

首先您必须解析文本,然后创建一个日期对象,然后添加 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

我认为这篇文章中的所有其他答案(没有日期对象)都是不正确的。

您可以使用 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

【讨论】:

  • 因为我只想从电影长度中获取特定电影节目的结束时间。所以这个答案也解决了我的疑问。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2015-12-29
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多