我在获取两个时间戳(纪元格式)之间的时差方面存在问题。
我使用moment().format("L LT")
将其转换为所需的日期时间格式(MM/DD/YYYY HH:MM (12 hour)
),
但现在问题是,我想要hh:mm
P.S。:它也可能超过24小时。
我尝试了什么:
let timeDiffms,duration,timedifference,
start moment(startTimeStampInMS).format("L LT"),
end = moment(endTimeStampInMS).format("L LT");
timeDiffms = moment(end, "MM/DD/YYYY HH:mm").diff(moment(start, "MM/DD/YYYY HH:mm"));
duration = moment.duration(timeDiffms);
timedifference = Math.floor(duration.asHours()) +":"+duration.minutes(); // result
//output I am getting
// start = "03/20/2017 3:11 PM" end="03/21/2017 9:45 AM" timedifference = "30:24", (incorrect)
// start = "03/20/2017 10:07 AM" end="03/23/2017 11:24 AM" timedifference = "73:17" (correct)
// start = "03/20/2017 3:11 PM" end="03/23/2017 11:31 AM" timedifference = "80:20" (incorrect) strange
我不知道这里发生了什么问题。
答案 0 :(得分:5)
根据之前给出的答案,我能够解决相同的逻辑并为我的问题找到正确的解决方案。
let start moment(startTimeStampInMS),
end = moment(endTimeStampInMS);
let timediffms = end-start; // difference in ms
let duration = moment.duration(timediffms);
// _data should not be used because it is an internal property and can
//change anytime without any warning
//let hours = duration._data.days*24 + duration._data.hours;
//let min = duration._data.minutes;
let hours = duration.days()*24+ duration.hours();
let min = duration.minutes();
timeDifference = hours +":"+ min; // Answer
答案 1 :(得分:3)
在当前的解决方案中,您将一个时刻对象格式化为字符串,然后将该字符串解析回来以获得diff
。没有必要执行这个两步过程,您可以执行以下操作来获取持续时间:
start moment(startTimeStampInMS),
end = moment(endTimeStampInMS).format("L LT");
timeDiffms = end.diff(start);
duration = moment.duration(timeDiffms);
或者因为您的输入是以毫秒为单位:
moment.duration(endTimeStampInMS - startTimeStampInMS);
要获得duration
格式的HH:mm
,您可以使用CustomProperties
插件将format
方法添加到持续时间对象。
这是一份工作样本:
// Example milliseconds input
let startTimeStampInMS = 1490019060000;
let endTimeStampInMS = 1490085900000;
// Build moment duration object
let duration = moment.duration(endTimeStampInMS - startTimeStampInMS);
// Format duration in HH:mm format
console.log( duration.format('HH:mm', {trim: false}));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
&#13;