gpt4 book ai didi

javascript - 时间差返回 NaN

转载 作者:行者123 更新时间:2023-11-28 19:53:29 25 4
gpt4 key购买 nike

我想找出两个日期(或时间,不知道怎么说)之间的秒数差异。

这是代码:

var montharray = new Array ("Jan" , "Feb" , "Mar" , "Apr" , "May" , "Jun" , "Jul" , "Aug" , "Sept" , "Oct" , "Nov" , "Dec")
function time_difference (yr,m,d,h,mins,sec){
var today = new Date();
var this_year = today.getYear();
if (this_year<1000)
this_year+=1900;
var this_month= today.getMonth();
var this_day=today.getDate();
var this_hour=today.getHours();
var this_mins=today.getMinutes();
var this_secs=today.getSeconds();
var today_string=montharray[this_month]+" "+this_day+", "+this_year+" "+this_hour+" "+this_mins+" "+this_secs;
var disconnect_string=montharray[m-1]+" "+d+", "+yr+" "+h+" "+mins+" "+sec;
var difference=(Math.round((Date.parse(disconnect_string)-Date.parse(today_string))/1000)*1)
alert(difference);
}
time_difference(2014,4,13,16,0,0)

(在我的国家,我提问的时间是15:26)

但警报显示 NaN。

但是当我仅使用年、月、日时,它会返回预期结果 1。

标点符号有问题还是......?

最佳答案

使用方法getTime。它返回日期的 UNIX 偏移量(以毫秒为单位)。

var date1= new Date();
var date2 = new Date("2013-01-01");

var difference = (date1.getTime() - date2.getTime()) / 1000;

如果您不知道两个日期中哪一个较早,可以对结果使用 Math.abs

difference = Math.abs(difference);

关于javascript - 时间差返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23030384/

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