0

I am calculating the number of days between the 'from' and 'to' date. For example, if the from date is mm/dd/yyyy and the to date is mm/dd/yyyy. How do I get the result using JavaScript?

from date is like:11/25/2014 to date is like :11/27/2014

I need result as 2 by using javascript>

User
  • 1,644
  • 10
  • 40
  • 64
  • 2
    have a look at this library [date.js](http://www.datejs.com/) – Mivaweb Nov 27 '14 at 10:33
  • Also I would suggest [MomentJS](http://momentjs.com/). Btw for serious work you would definitely need a library. The edge cases are a lot when you do manipulation with dates. – drinchev Nov 27 '14 at 10:52

4 Answers4

1

The implementation from John Resig:

// Get date difference.
// @see http://ejohn.org/projects/javascript-pretty-date/
function prettyDate(date, now){
    var diff = (((now || (new Date())).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);

    if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31)
        return this.format(date, 'yyyy-mm-dd');

    return day_diff == 0 && (
            diff < 60 && "Just now" ||
            diff < 120 && "1 minute ago" ||
            diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            diff < 7200 && "1 hour ago" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
        day_diff == 1 && "yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
},
Joy
  • 9,430
  • 11
  • 44
  • 95
0

Try this :

var date1 = new Date("11/28/2014");

var date2 = new Date("11/27/2014");

var date_difference=parseInt((date1-date2)/(24*3600*1000));

alert(date_difference);

Hope it helps!

Raghvendra Kumar
  • 1,328
  • 1
  • 10
  • 26
0

You need number of days than below is the solution :-

var _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {

   // Discard the time and time-zone information.
   var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
   var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

   return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
ostrgard
  • 380
  • 3
  • 9
0

you can try this code

<script>
var d1 =Date.parse("11/27/2014");   // will give the number of milisenonds passed from 01 January, 1970 00:00:00 Universal Time (UTC)
var d2=Date.parse("11/25/2014");
var miliInDay= 1000*60*60*24; // total milliseconds in 24 hour
var diff= d1-d2;
var dateDiff= diff/miliInDay;


</script>
Ashwin
  • 431
  • 1
  • 5
  • 11