Reputation: 693
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, i don't even know if it is possible, to do this with Javascript. I guess that it is,but that is just a guess.
Here is the html that I have:
<div class="span3" id="checkin">
<span class="text-label"><i class="icon-calendar"></i>Check In</span>
<input type="text" name="checkin" value="02/08/2014">
</div>
<div class="span3" id="checkout">
<span class="text-label"><i class="icon-calendar"></i>Check Out</span>
<input type="text" name="checkout" value="04/08/2014">
</div>
Those two fields are actually bootstrap date pickers. They always come with some default values. Now, I want when user change those two values to calculate the difference between two dates (alert or console log will do, I will find my way from there).
Problem is that I have no clue where to start and how to do that calculation. Again I guess that onchange event may be a good candidate but...I have no idea how to calculate the difference.
Any help will be deeply appreciated.
Regards, John
Upvotes: 0
Views: 290
Reputation: 24559
<script type="text/javascript">
//Set the two dates
today=new Date()
var christmas=new Date(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScript
if (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 milliseconds
var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
document.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!
Upvotes: 0
Reputation: 3118
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 = new Date(start[2], start[1]-1, start[0]);
var endDate = new Date(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.
Upvotes: 3