Monday, 7 April 2014

Difference between 2 Dates - Javascript

This Script finds the difference between 2 dates. The result is Days Count.

Date Object. 

Initializing Dates
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString) // mm/dd/yyyy format
new Date(year, month, day, hours, minutes, seconds, milliseconds)

example 

   Difference between 04/04/2014 and 04/08/2014 is 1.

Code Block

 

<html>
<head>
<script type="text/javascript">
    function getDateDifference()
    {
        var date1 = new Date("20/04/2014");
        var now = new Date();
        var timeDiff = (date1.getTime() -now.getTime());  // gets the timeDifference in milliseconds.
        /* Converts the TimeDifference to Total no of days  
            3600- Time for 1 hr in secs  (60*60);
            3600*24 - Time for 1 day in secs.
            1000 * 3600*24 - Time  for 1 day in milliseconds.
           The Math.ceil(x) function returns the smallest integer greater than or equal to a number "x".
      */
             diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
        alert(diffDays);
    }
</script>
</head>
    <body>      
        <script>getDateDifference();</script>
    </body>
</html>


References

  1. http://www.w3schools.com/js/js_obj_date.asp

No comments:

Post a Comment