AS2:计算两个日期之间的天数

时间:2011-09-01 10:00:43

标签: flash actionscript

我目前使用此脚本来确定两个日期之间的差异:

// Slide_Tracker[?].date_int are results from the built in function getTime()
var current_date = new Date(Slide_Tracker[i].date_int);
var past_date:Date = new Date(Slide_Tracker[i - 1].date_int);
var date_diff:Number = Math.round((current_date - past_date) / 86400000);

这个问题是我想要监控实际的实际日期变化,所以如果有人在晚上11:59访问了该应用程序,然后在5分钟后回来,这将记录为1天的差异(新的一天),这当前脚本需要至少12个小时才能在两个日期之间通过,以便将其注册为新的一天。

我已经考虑过使用日期编号等,但由于月份和年份差别很大,因此路线非常复杂,必须有更简单的东西。

2 个答案:

答案 0 :(得分:1)

作为一个FYI,下一个AM的日期和午夜之间的差异是:

// dt is the start date
var diff:Number = 
      new Date(dt.getYear(), dt.getMonth(), dt.getDate() + 1) - dt.getTime()

但最简单的方法是简单地转到第二天,然后从那里开始:

var dt:Date = new Date(Slide_Tracker[i - 1].date_int);
var past_date = // start at the next day to only deal w/ 24 hour increments
    new Date(dt.getYear(), dt.getMonth(), dt.getDate() + 1);
dt = new Date(Slide_Tracker[i].date_int);
var current_date = 
    new Date(dt.getYear(), dt.getMonth(), dt.getDate() + 1);
var date_diff:Number = Math.round((current_date.getTime() - 
                                   past_date.getTime()) / 86400000);

您的另一个选择是对输入进行舍入:

// rounds a timestamp *down* to the current day
function getBaseDay(val:Number):Number
{
    return Math.floor( val / 86400000 ) * 86400000
}

var current_date = new Date(getBaseDay(Slide_Tracker[i].date_int));
var past_date:Date = new Date(getBaseDay(Slide_Tracker[i - 1].date_int));
var date_diff:Number = Math.round((current_date.getTime() - 
                                   past_date.getTime()) / 86400000);

答案 1 :(得分:0)

这样的事情应该有效:

public boolean isNewDay( current:Date, past:Date ):Boolean
{
    // check the days of the month first
    if( current.date != past.date )
        return true;

    // check the months in case they came back on the same day of the next month
    if( current.month != past.month )
        return true;

    // finally check the year, in case they came back on the same day the next year
    if( current.fullYear != past.fullYear )
        return true;

    return false;
}

即使你已经接受了答案,这里还有一个更新功能:

public function getNumberOfDays( current:Date, past:Date ):int
{
    // get the number of millis between the two dates
    var millis:Number = current.time - past.time;

    // a day in millis is 1000 (s) * 60 (m) * 60 (h) * 24 (day)
    var day:Number = 1000 * 60 * 60 * 24;

    // get the number of days
    var numDays:int = int( millis / day );

    // create midnight of the current day
    if ( numDays == 0 )
    {
        // if our numDays is 0, check if the current date is after midnight and the
        // previous date was before midnight the previous day, in which case, count
        // it as another day
        var midnight:Date = new Date( current.fullYear, current.month, current.date );
        if ( current.time > midnight.time && past.time < midnight.time )
            numDays++;
    }

    return numDays;
}

它适用于我尝试的所有测试用例(午夜至23.59.59 = 0天,23.59至00.05 = 1天)