简单的 javascript 日期数学......不是真的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6356164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:24:04  来源:igfitidea点击:

Simple javascript date math... not really

javascriptmathdate

提问by user799301

I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...

我正在尝试创建一个简单的脚本,根据从 2011 年 7 月 6 日星期三开始的双周计划为我提供下一个回收日期。所以我创建了这个简单的函数......

    function getNextDate(startDate) {
        if (today <= startDate) {
            return startDate;
        }
        // calculate the day since the start date.
        var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
        // check to see if this day falls on a recycle day 
        var bumpDays = totalDays%14;  // mod 14 -- pickup up every 14 days...
        // pickup is today
        if (bumpDays == 0) {
            return today;
        }
        // return the closest day which is in 14 days, less the # of days since the last
        // pick up..
        var ms =  today.getTime() + ((14- bumpDays) * one_day);
        return new Date(ms);
    }

and can call it like...

并且可以称之为...

 var today=new Date();
 var one_day=1000*60*60*24;  // one day in milliseconds
 var nextDate = getNextDate(new Date(2011,06,06));

so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..

到目前为止一切顺利……但是当我将“今天”投影到 2011 年 10 月 27 日时,我将 2011 年 11 月 8 日星期二作为下一个日期,而不是 2011 年 9 月 11 日星期三……事实上,从现在开始的每一天2011 年 10 月 26 日到 2011 年 10 月 26 日预测正确的取车时间...并且从 2011 年 10 月 27 日到 2012 年 2 月 28 日的每个日期都预测星期二而不是星期三。然后从 2/29/2012(闰年)到 10/24/2012(又是 10 月)的每个日期都正确地预测了星期三。我错过了什么?任何帮助将不胜感激..

V

回答by Exelian

The easiest way to do this is update the Dateobject using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.

最简单的方法是Date使用更新对象setDate。由于此答案的评论表明这不是规范的正式组成部分,但所有主要浏览器都支持它。

You should NEVERupdate a different Dateobject than the one you did the original getDatecall on.

永远不应该更新Date与您进行原始getDate调用的对象不同的对象。

Sample implementation:

示例实现:

var incrementDate = function (date, amount) {
    var tmpDate = new Date(date);
    tmpDate.setDate(tmpDate.getDate() + amount)
    return tmpDate;
};

If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.

如果您要增加日期,请使用此功能。它将接受正值和负值。它还保证使用的日期对象不会更改。如果您不希望更新更改对象的值,这应该可以防止可能发生的任何错误。



Incorrect usage:

错误用法:

var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)

This will update the "date" value for startDatewith 14 days based on the value of a. Because the value of ais not the same is the previously defined startDateit's possible to get a wrong value.

这将startDate根据 的值更新14 天的“日期”值a。因为 的值a与之前定义的值不同,startDate所以可能会得到错误的值。

回答by yalarad

Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:

扩展 Exellian 的答案,如果你想计算未来的任何时期(在我的例子中,下一个支付日期),你可以做一个简单的循环:

var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);

while (basePayDate < today) {
    basePayDate.setDate(basePayDate.getDate()+14);
}

var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);

document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());

This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...

假设核心日期服务按预期工作,这不会遇到奇怪的问题。我不得不承认,我没有在未来多年内对其进行测试......

回答by Debby

Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:

注意:我有一个类似的问题;我想每周创建一个日期数组,即开始日期 10/23/2011 并持续 12 周。我的代码或多或少是这样的:

var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);

var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();

dateArray[0] = myDate.format('m/d/Y');

for (var count = 1; count < numberOccurrences; count++) {
    milliseconds += week;
toDate.setTime(milliseconds);
    dateArray[count] = toDate.format('m/d/Y');
}

Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.

因为我没有指定时间而且我住在美国,所以我的默认时间是午夜,所以当我越过夏令时边界时,我搬到了前一天。哎呀。我通过在进行周计算之前将一天中的时间设置为中午来解决它。