Skip to content Skip to sidebar Skip to footer

Date Difference In Days In Javascript?

I know how to use javascript, but i have no in depth knowledge of it. I know how I can get the date difference in days in PHP but in this case, I need javascript solution. Honestly

Solution 1:

You could first parse your string an create a JavaScript date like that:

var start= $("input[name=checkin]").val().split("/");
var end= $("input[name=checkout]").val().split("/");

var startDate =newDate(start[2], start[1]-1, start[0]);
var endDate =newDate(end[2], end[1]-1, end[0]);

Then you can simply substract the dates from each other:

endDate - startDate

That substraction will give you the time difference in milliseconds. To convert that to days, simply divide it by the number of milliseconds in a day (1000 * 60 * 60 * 24).

Now you have the difference in days. For an example, see JSFiddle.

Solution 2:

<scripttype="text/javascript">//Set the two dates
today=newDate()
var christmas=newDate(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScriptif (today.getMonth()==11 && today.getDate()>25) //if Christmas has passed already
christmas.setFullYear(christmas.getFullYear()+1) //calculate next year's Christmas//Set 1 day in millisecondsvar one_day=1000*60*60*24//Calculate difference btw the two dates, and convert to daysdocument.write(Math.ceil((christmas.getTime()-today.getTime())/(one_day))+
" days left until Christmas!")

This short Javascript will display the DAY difference between today (value 1) and christmas (your value 2). Ovbioulsy these can be replaced with our two values and should then work.

Example: 146 days left until Christmas!

Solution 3:

var date1 = newDate("7/11/2010");
var date2 = newDate("12/12/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays)​;

Try this . i found it from this link

Post a Comment for "Date Difference In Days In Javascript?"