How to get date difference in javascript

I defined two variables

var startdate = new Date();
var enddate = new Date();

I get dateassigned to the startdate from a function. I then assign the start date value
to the enddate variable and I'm doing some for loop logic where I compare the dates and
in that process I want to see the date difference between startdate and enddate. I get
diff as NAN when I substrace like var diff = startdate - datediff.

When I put alert on startdate it comes as: 2010-06-28 00:00:00.

I'M not sure what could be wrong.

Thanks
vmandemAsked:
Who is Participating?
 
HonorGodConnect With a Mentor Software EngineerCommented:
This article should help

2 Dates - What's the difference?

http://www.experts-exchange.com/A_483-2-Dates---What%27s-the-difference?.html
0
 
Anil GolamariConnect With a Mentor Commented:
<script type="text/javascript">

//Set the two dates
var enddate =new Date(2010, 0, 1) //Month is 0-11 in JavaScript
var startdate =new Date()
//Get 1 day in milliseconds
var one_day=1000*60*60*24

//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((startdate.getTime()-enddate.getTime())/(one_day))+
" days between start date and enddate!")

</script>

Hope it helps you.
0
 
vmandemAuthor Commented:
My problem is I pass the date exactly as it comes from external source and it comes in the format I told above and the dates are dynamic and changes. I cannot hard code for one date like you shown. I don't know I have to format like getting 8/10/2010. I can ignore the time and time is not a factor here.
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
Anil GolamariCommented:
<script language=javascript>
function daysDiff(eD, eT, sD, sT) {
var endDate = eD.split("/");
var dy2 = endDate[0];
var mo2 = endDate[1];
var yr2 = endDate[2];
var startDate = sD.split("/");
var dy1 = startDate[0];
var mo1 = startDate[1];
var yr1 = startDate[2];
var endTime = eT.split(":");
var hr2 = endTime[0];
var mn2 = endTime[1];
var startTime = sT.split(":");
var hr1 = startTime[0];
var mn1 = startTime[1];
return diff = daysElapsed(new Date(yr2,MO2-1,dy2,hr2,mn2),new Date(yr1,MO1-1,dy1,hr1,mn1));
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

Try this code and you can change the format of the code in which ever form you want.
function daysElapsed(date1,date2) {
var difference =
Date.UTC(y2k(date1.getYear()),date1.getMonth(),date1.getDate(),date1.getHours(),date1.getMinutes(),0 )
- Date.UTC(y2k(date2.getYear()),date2.getMonth(),date2.getDate(),date2.getHours(),date2.getMinutes(),0 );
var retVal = difference/1000/60;
return retVal;
}
</script>
0
 
vmandemAuthor Commented:
Basically the fundamental problem I have is the value is not converted to date, here is what happening

        startDate = new Date(datevalue);

datevalue is a string value coming as : 2010-06-28 00:00:00
       
then I did some thing like this to see what is happening
        iDay = startDate .getDate();
        iMonth = startDate .getMonth();
        iYear = startDate .getFullYear();

        sDisplayDate = iMonth + "/" + iDay + "/" + iYear;
        alert(sDisplayDate);


IN THE ALERT I GET LIKE: NaN/NaN/NaN, so it looks like it is not converting. Once it is converted then I can use your funciton but not able to get this one initially.
0
 
HonorGodSoftware EngineerCommented:
Ah, so you know that the input date string is like this:

2010-06-28 00:00:00

I would:
- split the string into 2 pieces at the space
- reformat the date portion, then
- pass the reformated string to the Date object constructor:


<html>
<body>

<script type='text/javascript'>

var str = '2010-06-28 00:00:00'
var info = str.split( ' ' );
var ymd = info[ 0 ].split( '-' );

var when = new Date( ymd[ 1 ] + '/' + ymd[ 2 ] + '/' + ymd[ 0 ] + ' ' + info[ 1 ] )

document.write( when );

</script>

</body>
</html>

Open in new window

0
 
Anil GolamariCommented:
selectedDateTime = "2010-06-28 00:00:00"
var splitarray = new Array();
splitarray= selectedDateTime.split(" ");


Try this to split date from datetime
0
 
HonorGodSoftware EngineerCommented:
Easier...

To convert a string (s)  in this form:
   2010-06-28 00:00:00
To one in this form:
   2010/06/28 00:00:00

Use can use this

  s.replace( /-/g, '/' )

and this can be passed to the Date object constructor to instantiate a valid date object.
<html>
<body>

<script type='text/javascript'>

var s = "2010-06-28 00:00:00"
document.write( s.replace( /-/g, '/' ) + '<br>' );
var d = new Date( s.replace( /-/g, '/' ) );
document.write( d );

</script>

</body>
</html>

Open in new window

0
 
HonorGodSoftware EngineerCommented:
Thanks for the grade & points.

Good luck and have a great day.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.