我想计算Date.parse
生成的两个时间戳之间的小时数和分钟数。在我得到差异后,我需要将其转换为小时和分钟,如2.10
(意味着,2小时10分钟)。一旦我读完了它就需要将它除以3600,所以我尝试了这段代码,但它只是给了我0.89
而不是1.26
。
var now = new Date();
var endTime = Date.parse(now)/1000;
var startTime = Date.parse("2018-03-16 10:29:17")/1000;
$scope.timestamp_difference = startTime - endTime;
$scope.hours = $scope.timestamp_difference/3600;
如何正确做到?
答案 0 :(得分:0)
如果你还没有听说过,Momentjs在javascript中使用日期和时间非常容易我更新了代码,你可能希望它现在可以帮到你
var date1 = moment('03/15/2018 11:00', 'MM/DD/YYYY hh:mm'),
date2 = moment('03/16/2018 10:00', 'MM/DD/YYYY hh:mm');
var duration = moment.duration(date2.diff(date1));
//you will get 23 hours 00 minute
alert(duration.asHours().toFixed(2))
http://jsfiddle.net/dp7rzmw5/9771/
Output: 23:00 hrs
答案 1 :(得分:0)
function getTimeDifference(timestampDifference) {
var hours = ~~(timestampDifference / 3600);
var minuts = ~~((timestampDifference - hours * 3600) / 60);
var seconds = timestampDifference - hours * 3600 - minuts * 60;
return hours + '.' + minuts + '.' + seconds;
}
答案 2 :(得分:0)
var minutes = "0" + Math.floor(timestampDifference / 60);
// get minutes
var seconds = "0" + Math.floor(timestampDifference - minutes * 60);
// get seconds
var hour = "0" + Math.floor(timestampDifference / 3600);
//get hour
if ( hour > 1 ) {
return hour.substr(-2) + ":" + minutes.substr(-2) + ":" + seconds.substr(-2);
} else {
return minutes.substr(-2) + ":" + seconds.substr(-2);
}
// check if the hour is greater then 1 than return time with hour else return minutes.