JavaScript:显示到日期之间的差异,如重新标记时间。(当天和之前呢)
我想显示今天和选定日期时间之间的差异,以显示剩余时间 我使用了stack overflow中提到的解决方案。但是我今天有问题! 当选择的日期是今天或之前,我的意思是,当差异(JavaScript:显示到日期之间的差异,如重新标记时间。(当天和之前呢),javascript,date,datetime,Javascript,Date,Datetime,我想显示今天和选定日期时间之间的差异,以显示剩余时间 我使用了stack overflow中提到的解决方案。但是我今天有问题! 当选择的日期是今天或之前,我的意思是,当差异(diffDays)不是正的时候,我得到了错误的结果。我该怎么办 $("#ServiceTime").change( function (e) { var firstDate = $(this).val(); var secondDate = new Date(); v
diffDays
)不是正的时候,我得到了错误的结果。我该怎么办
$("#ServiceTime").change(
function (e) {
var firstDate = $(this).val();
var secondDate = new Date();
var diffDays = firstDate.getTime() - secondDate.getTime();
var date = new Date(diffDays);
var str = '';
str += date.getUTCDate()-1 + " days and ";
str += date.getUTCHours() + " hours and ";
str += date.getUTCMinutes() + " minutes";
str += "remained...";
$("#remainedHourToService").html(str);
});
更新:
我不能单独使用abs
,如果用户选择过去两天,他将再次看到“1天58分钟和…”但我想要0天0分钟。。。。保留' 只需使用Math.abs()即可获得绝对值
$("#ServiceTime").change(function (e) {
var firstDate = $(this).val();
var second
Date = new Date();
var diffDays = Math.abs(firstDate.getTime() - secondDate.getTime());
var date = new Date(diffDays);
var str = '';
str += date.getUTCDate()-1 + " days and ";
str += date.getUTCHours() + " hours and ";
str += date.getUTCMinutes() + " minutes";
str += "has remained...";
$("#remainedHourToService").html(str);
});
更新:
这个问题很容易解决。:)
如果你能回答这个问题,或者告诉我为什么它需要下降,我会很感激。如果你要计算从现在到过去某个时间的差异,那么结果将是负数。如果只使用绝对值,则会得到实际的差值。如果结果为负,只需输入一个条件以返回0。
$("#ServiceTime").change(function (e) {
var firstDate = $(this).val();
var second
Date = new Date();
var diff = firstDate.getTime()-secondDate.getTime();
var str2 = "";
if(diff > 0)
str2 = "have remained...";
else
str2 = "have passed...";
var diffDays = Math.abs(diff);
var date = new Date(diffDays);
var str = '';
str += date.getUTCDate()-1 + " days and ";
str += date.getUTCHours() + " hours and ";
str += date.getUTCMinutes() + " minutes";
str += str2;
$("#remainedHourToService").html(str);
});