How to calculate a number of days between 2 date

Discussion in 'JavaScript' started by windy417, Jul 20, 2006.

  1. #1
    Dear all,

    I have the following script:

    var Day1 = dateObj1.value.substring( 0, 2 );
    var Month1 = dateObj1.value.substring( 3, 5 );
    var Year1 = dateObj1.value.substring( 6, 10 );
    var Dt1 = Year1 + Month1 + Day1;


    var Day2 = dateObj2.value.substring( 0, 2 );
    var Month2 = dateObj2.value.substring( 3, 5 );
    var Year2 = dateObj2.value.substring( 6, 10 );
    var Dt2 = Year2 + Month2 + Day2;

    if( Dt1 > Dt2 || Dt1 == "" || Dt2 == "")
    {

    return true;

    }

    For example, if Dt1 value is 20050601 and Dt2 value is 20050523, how can i get the number of days?. besides that, i also want to check the condition if Dt1 value <=Dt2 + 60 prompt messgae"ok" otherwise prompt message "<= 60days of PPC date"

    Any helps is highly appreciated.

    Thanks in advance...
     
    windy417, Jul 20, 2006 IP
  2. T0PS3O

    T0PS3O Feel Good PLC

    Messages:
    13,219
    Likes Received:
    777
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Convert each date to Unix time first, which will give you the number of seconds since Jan 1st 1970 (I think). All languages I know of have a function for that so JS must have it as well.

    Then you can substract the earlier date from the later date and the difference is the number of seconds between them Seconds to days conversion should be childsplay form there.
     
    T0PS3O, Jul 20, 2006 IP
  3. coderlinks

    coderlinks Peon

    Messages:
    282
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi,
    You can do this:

    var d1 = dateObj1.getTime();
    var d2 = dateObj2.getTime();
    var days = (d1-d2)/(1000*60*60*24);

    This assumes d1>d2, use d2-d1 if you know d2>d1. The 'days' variable should contain the no. of days between the two dates.

    It should work. I haven't tested it though.

    Thomas
     
    coderlinks, Jul 23, 2006 IP