Solved

How to get date difference in javascript

Posted on 2010-08-13
9
576 Views
Last Modified: 2013-11-11
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
0
Comment
Question by:vmandem
  • 4
  • 3
  • 2
9 Comments
 
LVL 18

Assisted Solution

by:Anil Golamari
Anil Golamari earned 38 total points
Comment Utility
<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
 

Author Comment

by:vmandem
Comment Utility
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
 
LVL 18

Expert Comment

by:Anil Golamari
Comment Utility
<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
 
LVL 41

Accepted Solution

by:
HonorGod earned 37 total points
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:vmandem
Comment Utility
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
 
LVL 41

Expert Comment

by:HonorGod
Comment Utility
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
 
LVL 18

Expert Comment

by:Anil Golamari
Comment Utility
selectedDateTime = "2010-06-28 00:00:00"
var splitarray = new Array();
splitarray= selectedDateTime.split(" ");


Try this to split date from datetime
0
 
LVL 41

Expert Comment

by:HonorGod
Comment Utility
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
 
LVL 41

Expert Comment

by:HonorGod
Comment Utility
Thanks for the grade & points.

Good luck and have a great day.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now