Javascript时差计算

时间:2013-07-24 14:12:49

标签: javascript datetime time

我有这个功能

function timeCalculator(form)
{
    var currentTimeAndDate = new Date();
    var userTimeAndDate = form.userDate.value;
    var userUTCOffset2 = form.userUTCOffset.value;
    var userDate = new Date(userTimeAndDate);
    var tzDifference = currentTimeAndDate.getTimezoneOffset() + (userUTCOffset2 - currentTimeAndDate.getTimezoneOffset());
    var timeDifference = new Date((userDate.getTime()+(tzDifference*60*1000))-(currentTimeAndDate.getTime()+(userDate.getTimezoneOffset()*60*1000)));

    var hours = Math.floor(timeDifference.getTime() / 36e5),
    minutes = Math.floor(timeDifference.getTime() % 36e5 / 60000),
    seconds = Math.floor(timeDifference.getTime() % 60000 / 1000);

    document.getElementById('result').innerHTML = "There is exactly "+hours+" hours,"+minutes+"minutes and "+seconds+" seconds left until your specified time.";
}

这应该做的是用户在表单中输入时间,日期和UTC偏移量,并根据它计算到该点之前剩余的时间。分钟和秒似乎工作正常,但小时有问题。任何人都有任何建议或可能采取不同的方法来做这样的事情?另外,我如何在差异中添加天,月,年?

1 个答案:

答案 0 :(得分:2)

我建议使用moment.js。它会为你带来很多悲伤。

function timeCalculator(form)
{
    // get a moment based on the user input
    var m = moment(form.userDate.value).zone(form.userUTCOffset.value);

    // calculate a duration of time passed between now and that moment
    var now = moment();
    var d = moment.duration(m - now);

    // build your output string
    var s = d.hours() + " hours, " +
            d.minutes() + " minutes, and " +
            d.seconds() + " seconds";

    // set the output html
    document.getElementById('result').innerHTML = "There are exactly " + s +
                                          " left until your specified time.";
}

这假定选择了未来的日期,并且您总是希望显示小时,分钟和秒。

您可以考虑使用更通用的方法,该方法显示到期或剩余时间的近似值

function timeCalculator(form)
{
    // get a moment based on the user input
    var m = moment(form.userDate.value).zone(form.userUTCOffset.value);

    // get a humanized duration string
    var s = m.fromNow(true);

    // set the output html
    document.getElementById('result').innerHTML = "There are " + s +
                                          " left until your specified time.";
}

有关预期输出的详细信息,请参阅fromNow上的文档。

顺便说一句,传递表单并将结果设置为硬编码元素似乎有点奇怪。您可能只想传入表单值并返回字符串结果,让函数的调用者处理它们的来源并转到。