Results 1 to 2 of 2

Thread: Difference Between Two Date

  1. #1
    Join Date
    Nov 2006
    Location
    Jakarta
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Difference Between Two Date

    I want to asking about how to get a date difference in javascript :

    example :

    Let say we have two textbox, the first one we call start date and the second one we call last date.

    start date contain data 2006-11-06 08:20:21 and last date contain 2006-11-10 09:10:21.

    How can we get the value of 4 days between those data in the textbox...

    Thank You very much for your answer...
    Last edited by baltazhor200401; 11-07-2006 at 12:54 AM.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    To literally get the number of days between those two date time values, you would do this:

    Code:
    (new Date(2006,11,10,9,10,21).getTime()-new Date(2006,11,6,8,20,21).getTime())/(1000*60*60*24)
    Of course, that works out to:

    4.034722222222222 days

    So you could use the Math.round() method:

    Code:
    Math.round((new Date(2006,11,10,9,10,21).getTime()-new Date(2006,11,6,8,20,21).getTime())/(1000*60*60*24))
    which will give you 4 in this case. Alternatively, you could omit the H,M,S to begin with:

    Code:
    (new Date(2006,11,10).getTime()-new Date(2006,11,6).getTime())/(1000*60*60*24)
    which will also give you 4 in this case. However, if it was really closer to 3 or 5 days, you no longer can tell that.

    For flat rate per day charges with no allowance for partial days, for example, use Math.ceil() method:

    Code:
    Math.ceil((new Date(2006,11,10,9,10,21).getTime()-new Date(2006,11,6,8,20,21).getTime())/(1000*60*60*24))
    which works out to 5 in this same case.

    Finally, if partial days do not count, even if they consist of 23 hours, 59 minutes and 59 seconds - use Math.floor().
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •