4 Replies Latest reply on Jul 3, 2007 9:27 PM by doug777

    subtracting dates

    MyronCope
      I am creating a string with date values and I would like to return a string that has the day that is 3 days back, however when I try to do this from today (7/2/07) it gives me a negative value, also I want the current month but instead of July its showing June.

      My code:

      <CODE>
      public var beginDate:String = (new Date().getMonth()) + "/" + (new Date().getDate() - 3) + "/" + (new Date().fullYear.toString());
      </CODE>

      <OUTPUT>
      6/-1/2007
      </OUTPUT>

      what am I doing wrong here? Is there a way to get the (pseudocode) DAte.Now.Day-3 and then convert the whole date to something like mm/dd/yy? Thanks
        • 1. Re: subtracting dates
          BarryGee
          The date is in us format i.e. month/date/year. If you take 3 from 2 thats -1, you would need to write some sort of loop if you want it to jump back a month say from the 2nd july to the 30th june if you take 3 days off.
          • 2. Re: subtracting dates
            MyronCope Level 1
            What I am thinking now is this: create a test variable like this:
            <CODE>
            public var test:Number = (new Date().day -3);
            </CODE>

            and then check if the var is less than 1, meaning that I will have to get the previous month and then subtract from the prev. months days inside the CreationComplete handler:

            <CODE>
            if (test < 1)
            {
            //day is less than one, find the number of days in the previous month and do the following
            //1: add 1 to the test var
            //2. do this: NumberOfDaysOfPrevMonth - test

            }
            else
            {
            //day is 1 or bigger, just subtract from the current month
            beginDate = (new Date().getMonth()) + "/" + (new Date().getDate() - 3) + "/" + (new Date().fullYear.toString());
            }
            </CODE>

            What is the syntax for finding the number of days of the previous month? (steps 1 and 2 in the first part of the if stmt). thanks
            • 3. Re: subtracting dates
              Oddsy Level 1
              The month problem you're having is because Date's months are zero-based, i.e. 0 is January, 1 is February, etc.
              • 4. Re: subtracting dates
                doug777 Level 1
                The best way to do this is to use the getTime() function.

                e.g.
                date3DaysBack = new Date(currentDate.getTime() - 3 * 24*60*60*1000);

                Doug