使用JavaScript计算剩余天数到特定日期 [英] Calculate days left to a specific date with JavaScript

查看:73
本文介绍了使用JavaScript计算剩余天数到特定日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算到特定日期为止的剩余天数.我知道有上百万种不同的方法和教程,但是我想自己写一个代码.问题在于该函数的输出为"NaN".非常感谢您的帮助.

I was trying to calculate the days left until a specific date. I know that there are a million different approaches and tutorials about it, but I wanted to write a code by myself. The problem is that the output of the function is "NaN". I am very thankful for your help.

这是我的代码:

var daysLeft = function(input) {
    var num = '';
    var date = [];
    var x = 0;
    for (i = 0; i < input.length; i++) {
        if (!isNaN(input.charAt(i))) {
            num += input.charAt(i);
        }
        else {
            date[x] = parseInt(num, 10);
            x++;
        }
    }
    var inputDate = new Date(date[2], date[1], date[0]);
    var today = new Date();
    var timeDiff = Math.abs(inputDate.getTime() - today.getTime());
    return Math.ceil(timeDiff / (1000*3600*24));
};

daysLeft("11.12.2014"); 

顺便说一句:我写了这段代码,因为Date()函数适用于日期的美国格式(MM/dd/YYYY),而不适用于UTC日期.我也知道有Date.UTC()函数,但是无论如何.我只是想自己转几天又几天.

BTW: I wrote this code, because the Date() function works with the American format of Dates (MM/dd/YYYY) and not with UTC dates. I am also aware that there is the Date.UTC() function, but anyway. I just wanted to turn around months and days myself.

推荐答案

当解析 num 以设置 date [x] 时,您需要重置 num''.

When you parse num to set date[x], you need to reset num to ''.

...
else {
    date[x] = parseInt(num, 10);
    x++;
    num = '';
}

您可以考虑使用 String.split() 来分隔句点中的输入.

You might consider using String.split() to separate your input at the periods.

这篇关于使用JavaScript计算剩余天数到特定日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆