如何在JavaScript / JQuery中减去24小时制?

时间:2018-12-05 20:25:24

标签: javascript jquery

我有两个时间值,应减去并输出小时差。例如,我以以下格式获取值:

0530-2400

该值是一个字符串。我想转换为JavaScript Date对象是第一步。这是我到目前为止的内容:

var time = "0530-2400",
    arr = [];
arr = time.split('-');

var dateObj = new Date(),
    hours1 = dateObj.setHours(Number(arr[0].substring(0, 2))),
    hours2 = dateObj.setHours(Number(arr[1].substring(0, 2))),
    minutes1 = dateObj.setMinutes(Number(arr[0].substring(2, 4))),
    minutes2 = dateObj.setMinutes(Number(arr[1].substring(2, 4)));
    
console.log(hours1);
console.log(minutes1);
console.log(hours2);
console.log(minutes2);

我上面显示的时间输出应为18.5小时。如果我们减去24-5.5(530) = 18.5

增量始终为15、30或45分钟。是否有转换字符串然后在JS中进行数学运算的好方法?

3 个答案:

答案 0 :(得分:1)

如果几天之内不能有几个小时,您可以使用简单的数学方法做到这一点:

var time = "0530-2400",
    difference = calcDifference(time);

console.log(difference);

function calcDifference(time) {
  var arr = time.split('-').map(function(str) {
    var hours   = parseInt(str.substr(0, 2), 10),
        minutes = parseInt(str.substr(2, 4), 10);
    return (hours * 60 + minutes) / 60;
  });
  return arr[1] - arr[0];
}

答案 1 :(得分:1)

您在这里:

var time = "0530-2400",
arr = [];
arr = time.split('-');

var date1 = new Date(), date2 = new Date();
date1.setHours(Number(arr[0].substring(0, 2)));
date2.setHours(Number(arr[1].substring(0, 2)));
date1.setMinutes(Number(arr[0].substring(2, 4)));
date2.setMinutes(Number(arr[1].substring(2, 4)));
    
var msInAHour = 1000*60*60;
var msDiff = date2 - date1;
var diffInHours = msDiff/msInAHour;

console.log(diffInHours.toFixed(1));

提示:如果使用Moment.js,则使用日期要容易得多。

此处:https://momentjs.com/

这是该代码的更高级版本:

var dt = "0530-2400".split('-')
  .map(e=>new Date('1980-01-01'+e.replace(/(\d{2})(\d{2})/," $1:$2")));  
  
var diffInHours = ((dt[1]-dt[0])/(3600000)).toFixed(1);
console.log(diffInHours);

答案 2 :(得分:0)

var totalmin = 18.5*60
var min = total % 60;
var hours = (totalmin - min)/ 60;
  

分钟:30,小时:18

如果要将军事时间转换为标准时间:

if (hours > 0 && hours <= 12) {
  var standardHours= "" + hours;
} else if (hours > 12) {
  var standardHours= "" + (hours - 12);
} else if (hours == 0) {
  var standardHours= "12";
}
  

standardHours:6