Reputation: 3082
Sorry if this has been asked before, but I haven't been able to find anything. Here's essentially what I'm trying to do:
new Date(response.departureDate).getTime() - new Date(response.arrivalDate).getTime()
I need to calculate the total number of days (will always be a whole integer) between an arrival and departure date. These dates are strings, structured as 'YYYY-MM-DD'
.
How do I go about this?
Upvotes: 1
Views: 3243
Reputation: 213
Look at the Miles' answer here Just change it to:
function parseDate(str) {
var mdy = str.split('-')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
and use:
daydiff(parseDate(response.departureDate), parseDate(response.arrivalDate));
Upvotes: 1
Reputation: 582
You can use something like this
function countDays(date1, date2)
{
var one_day=1000*60*60*24;
return Math.ceil((date1.getTime()- date2.getTime()) /one_day);
}
countDays(new Date(response.departureDate), new Date(response.arrivalDate));
Upvotes: 0
Reputation: 1008
You can use regexp OR a much simpler approach would be to become familiar with MomentJS
API that lets you deal with dates in JS very smoothly (works in Node and browser)
It does add another tool to your toolbox, but as soon as you are manipulating dates, it is definetely worth it IMHO.
Way to go with MomentJS :
var depDate = moment(response.departureDate);
var arrDate = moment(response.arrivalDate);
var nbDays = depDate.diff(arrDate, 'days');
Upvotes: 1
Reputation: 261
I hope this example help for you
Apart from .diff(), you could also use moment durations: http://momentjs.com/docs/#/durations/
Example Fiddle: https://jsfiddle.net/abhitalks/md4jte5d/
Example Snippet:
$("#btn").on('click', function(e) {
var fromDate = $('#fromDate').val(),
toDate = $('#toDate').val(),
from, to, druation;
from = moment(fromDate, 'YYYY-MM-DD'); // format in which you have the date
to = moment(toDate, 'YYYY-MM-DD'); // format in which you have the date
/* using duration */
duration = moment.duration(to.diff(from)).days(); // you may use duration
/* using diff */
//duration = to.diff(from, 'days') // alternatively you may use diff
/* show the result */
$('#result').text(duration + ' days');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
From: <input id="fromDate" type='date' />
To: <input id="toDate" type='date' />
<button id="btn">Submit</button><hr />
<p id="result"></p>
Upvotes: 0
Reputation: 167220
You can use RegEx
to change them.
new Date(response.departureDate.replace(/-/g, "/")).getTime()
- new Date(response.arrivalDate.replace(/-/g, "/")).getTime()
So the RegEx .replace(/-/g, "/")
will replace all the -
to /
, and JavaScript will be able to read it right.
Upvotes: 0