0

While working with date difference, when I am using below code somehow function is assuming that all the months have 31 days. For ex. if I am subtracting 01-March with 28-February the difference is coming as 4 days. Is there any simple way to twick this. Any help will be appreciated.

function myFunction()
{

var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2);
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);



var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2);
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);


var x = document.getElementById("demo");
x.innerHTML=(n1-n)/(1000*24*60*60);

}
Kevin Brydon
  • 12,524
  • 8
  • 46
  • 76
  • 1
    For date manipulations you should better use a library such as [moment.js](http://momentjs.com/) as there are many pitfalls when working with dates – Andreas Mar 15 '13 at 11:59

3 Answers3

0

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

U can subtract like this--

var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01")  // some date
var diff = Math.abs(d1-d2);  // difference in milliseconds
var days = diff*24*60*60*1000;
Vitthal
  • 546
  • 3
  • 18
0

You code is actually subtracting March 1 from April 1, as the months in JavaScript dates are 0-based.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
0
var sysdt = "02/28/2013";
var date1 = new Date(sysdt);

var userdt = "03/01/2013"
var date2 = new Date(userdt);

var days = (date2-date1)/(1000*24*60*60);

or subtract 1 from month in your code

var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2)-1; // months are from 0 to 11
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);



var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2)-1; // months are from 0 to 11
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);

var days = (n1-n)/(1000*24*60*60);
Diode
  • 24,570
  • 8
  • 40
  • 51