开发者

How to calculate the difference between two ActionScript Date objects, in months?

I have to validate that 1) the end Date is not less than the start Date and 2) the difference between the two UTC Dates is not more than 12 months. To do this, I need a monthDifference function:

public static function monthDifference(start:Date, end:Date):int;

Si开发者_运维技巧nce partial months can be confusing, this is how month differences are supposed to work:

  • The month difference between January 1, 2010 and January 31, 2010 is zero (0).
  • The month difference between January 31, 2010 and February 1, 2010 is one (1).
  • The month difference between January 1, 2010 and February 28, 2010 is one (1).
  • The month difference between January 1, 2010 and March 1, 2010 is two (2).

How can I calculate month difference in ActionScript 3.0?


This is what I came up with...

public static function monthDifference(start:Date, end:Date):int {
    return (end.getUTCFullYear() - start.getUTCFullYear()) * 12 + 
        (end.getUTCMonth() - start.getUTCMonth());
} 

Please let me know if there's any error!


There is a pretty solid one listed here. I didn't find the authors name, udayms is his user name for the blog.

Pulled from his class:

private static function getMonths(date1:Date,date2:Date):Number{
  var yearDiff = getYears(date1,date2);
  var monthDiff = date1.getMonth() - date2.getMonth();
  if(monthDiff < 0){
    monthDiff += 12;
  }
  if(date1.getDate()< date2.getDate()){
    monthDiff -=1;
  }
  return 12 *yearDiff + monthDiff;
}


It is not so easy because you have to count with leap years! I think you should look at DateUtils.as from AS3Commons-lang library. There is a really useful method called addMonths() which could help you because it deals with invalid dates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜