1

我有这个功能

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 偏移量,并据此计算距离该点还剩多少时间。分钟和秒似乎工作正常,但小时有问题。任何人有任何建议或者可能对这样的事情有不同的方法吗?另外,我怎样才能在差异中添加天、月、年?

4

1 回答 1

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有关预期输出的详细信息,请参阅文档。

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

于 2013-07-24T18:45:43.763 回答