gpt4 book ai didi

javascript - JavaScript 中的日期格式

转载 作者:行者123 更新时间:2023-11-28 05:58:33 24 4
gpt4 key购买 nike

我想获取日期差异:

var dateString='2015-04-07T10:46:25Z';
var dt = new Date(value);
var now = new Date();
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
var utc1 = Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate());
var utc2 = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
var days=Math.floor((utc2 - utc1) / _MS_PER_DAY);//this is 415

结果必须采用以下格式:415d, 03:06:33

最好的方法是什么?我得到了日期,但缺少时间。

最佳答案

Try this

var datetime = new Date("2015-04-07T10:46:25Z");
var now = new Date();
if (datetime < now) {
var diffTime = now - datetime;
}else{
var diffTime = datetime - now;
}
var days = Math.floor(diffTime / 1000 / 60 / (60 * 24));

var dateDiff = new Date( diffTime );

var hour = dateDiff .getHours().toString().length == 1 ? '0' + dateDiff .getHours() : dateDiff .getHours();
var minute = dateDiff.getMinutes().toString().length == 1 ? '0' + dateDiff.getMinutes() : dateDiff.getMinutes();
var seconds = dateDiff.getSeconds().toString().length == 1 ? '0' + dateDiff.getSeconds() : dateDiff.getSeconds();

console.log(days + "d "+ hour + ":" + minute + ":" + seconds);

关于javascript - JavaScript 中的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37463718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com