将h:mm添加到当前时间

Add h:mm to current time

本文关键字:时间 添加 mm      更新时间:2023-09-26

希望在javascript中一起添加时间。

我从来没有写过任何javascript,因此我正在为前进的道路而奋斗。

我必须将4:00(4小时)添加到12:44(当前时间)。这在javascript中可能吗?

答案应报告回16:44

如果是的话,我该怎么办?

感谢

如果你把它分解成几个小的辅助函数,这并不难:

// Convert a time in hh:mm format to minutes
function timeToMins(time) {
  var b = time.split(':');
  return b[0]*60 + +b[1];
}
// Convert minutes to a time in format hh:mm
// Returned value is in range 00  to 24 hrs
function timeFromMins(mins) {
  function z(n){return (n<10? '0':'') + n;}
  var h = (mins/60 |0) % 24;
  var m = mins % 60;
  return z(h) + ':' + z(m);
}
// Add two times in hh:mm format
function addTimes(t0, t1) {
  return timeFromMins(timeToMins(t0) + timeToMins(t1));
}
console.log(addTimes('12:13', '01:42')); // 13:55
console.log(addTimes('12:13', '13:42')); // 01:55
console.log(addTimes('02:43', '03:42')); // 06:25

看看moment.js-一个管理各种时间相关功能的优秀库-momentjs.com

稍后添加回答:

你提到你是JavaScript新手,所以这里有一个简单的使用moment.js的问题的例子——这个例子假设文件和moment.jss在同一个文件夹中。查看moment.js上的文档,了解所有格式选项。祝你好运

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Add Time</title>
<script src="moment.js"></script>
</head>
<body>
   <script>
   //add 4 hours to the stated time
   var theFutureTime = moment().hour('12').minute('44').add(4,'hours').format("HH:mm");
   console.log(theFutureTime);  // prints 16:44
  </script>
</body>

使用moment.js可以将hh:mm转换为分钟并添加它们。

示例:

moment.duration("02:45").asMinutes() + moment.duration("02:15").asMinutes()

结果:300 mins

因此,您可以将分钟转换为hh:mm:

function timeConvert1(data) {
  var minutes = data % 60;
  var hours = (data – minutes) / 60;  
  return (hours + “:” + minutes);
}

用于添加时间格式字符串数组(包括秒,不计算天数)。

例如:

输入:times = ['00:00:10', '00:24:00']

输出00:24:10

// Add two times in hh:mm:ss format
function addTimes(times = []) {
    const z = (n) => (n < 10 ? '0' : '') + n;
    let hour = 0
    let minute = 0
    let second = 0
    for (const time of times) {
        const splited = time.split(':');
        hour += parseInt(splited[0]);
        minute += parseInt(splited[1])
        second += parseInt(splited[2])
    }
    const seconds = second % 60
    const minutes = parseInt(minute % 60) + parseInt(second / 60)
    const hours = hour + parseInt(minute / 60)
    return z(hours) + ':' + z(minutes) + ':' + z(seconds)
}
function addHours(start, end) {
var mins= moment.duration(start).asMinutes() + moment.duration(end).asMinutes();
  function z(n){return (n<10? '0':'') + n;}
  var h = (mins/60 |0) % 24;
  var m = mins % 60;
  return z(h) + ':' + z(m);
}