?
Solved

How to get date difference in javascript

Posted on 2010-08-13
9
Medium Priority
?
589 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
9 Comments
 
LVL 18

Assisted Solution

by:Anil Golamari
Anil Golamari earned 152 total points
ID: 33430831
<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
ID: 33430908
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
ID: 33431040
<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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 41

Accepted Solution

by:
HonorGod earned 148 total points
ID: 33431737
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
 

Author Comment

by:vmandem
ID: 33432245
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
ID: 33432294
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
ID: 33432429
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
ID: 33432925
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
ID: 33503047
Thanks for the grade & points.

Good luck and have a great day.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
This article discusses how to implement server side field validation and display customized error messages to the client.
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…
Suggested Courses

764 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