How to do Flex date deduction and addition

12,071

Solution 1

You can use the Date constructor for this. The first argument to Date's constructor takes either a year or a timestamp. You can use the Date.time property to get the timestamp from a date object. Once you have the timestamp you can add/subtract some number of seconds from it, and then pass it to new Date(timestamp) and you get a brand new date which represents the new timestamp.

Edit; As a commenter pointed out, time manipulation may not be the best way to go. But you can still use the Date constructor as follows:

var now:Date = new Date();
var threeMonthsAgo = new Date(now.fullYear, 
                              now.month - 3,  
                              now.date, 
                              now.hour, 
                              now.minute, 
                              now.second, 
                              now.millisecond);

The Date constructor is smart enough to deal with negative values, or values greater than 11.

Solution 2

Try the DateUtils open source library.

I use it extensively in the Flextras Calendar and it works great. I'm pretty sure there is a DateAdd method. To get a date 3 months earlier, you can just add a negative 3.

http://flexdateutils.riaforge.org/

Share:
12,071

Related videos on Youtube

leon
Author by

leon

Updated on April 26, 2022

Comments

  • leon
    leon about 2 years

    In flex, I am trying to do date deduction and addition, but couldn't find a way to do it.

    e.g.: public var dateNow:Date=new Date();

    How can I get the Date 3 months earlier than dateNow?

    Thanks!!!

  • JamesUsedHarden
    JamesUsedHarden about 14 years
    Date math is much more complicated than converting to seconds and adding/subtracting. You have to take time of day, days per month, leap years, time zones, and sometimes different contexts into account.
  • splash
    splash about 14 years
    Yes, but in case of the month it's not that difficult.
  • JabbyPanda
    JabbyPanda almost 13 years
    Even in case of the month it can be difficult :) When 2 – 1 = 2 when doing math operations with dates in ActionScript jabbypanda.com/blog/2011/09/…