SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2007
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Date difference in days

    Hi to all

    I want to find the difference between two dates in days. I am entering the first date in mm-dd-yyyy formate and second date i want to get the current date of the system and then get the difference in days.

    thanks in advance.

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    1. make the input a Date object-
    If you insist on your input format, you need to make an array of the date's pieces
    and convert them to numbers

    var val=inputval.split(/\D+/)
    var D1=new Date(val[2]*1,val[0]-1,val[1]*1);

    If you input a valid date string you can use Date.parse and skip the conversion-
    var inputvalue='3,27,2008' or '3/27/2008', or (depending on language) 'March 27,2008' (but not with hyphens)

    D1=new Date(Date.parse(inputvalue))


    2. get the current Date

    var D2=new Date();

    3.subtract the two, and divide the difference, which is in milliseconds, by the milliseconds in a day-

    var diff= Math.floor((D2-D1)/8.64e7)

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,871
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by mrhoo View Post
    If you input a valid date string you can use Date.parse and skip the conversion-
    var inputvalue='3,27,2008' or '3/27/2008', or (depending on language) 'March 27,2008' (but not with hyphens)
    or '27/3/2008' or '27 March, 2008' for those of us who live in countries that don't write our dates backwards.

    The main advantage of using Date.parse over a specific date format is that most people will not understand whichever single date format you choose because they don't use that format in their country whereas Date.parse will parse any valid date format that is acceptable in their country. It would even accept Japanese people entering the date with the year first.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  4. #4
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    or '27/3/2008' or '27 March, 2008' for those of us who live in countries that don't write our dates backwards
    Actually, the demon of the Date object thinks the Japanese are the ones who got it right....


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
  •