In JavaScript, I have two vars (aankomstDatum & vertrekDatum) containing a checkin date and a checkout date in the "dd-mm-yy" format. These vars come from text input fields with a jQuery datepicker.
I want to calculate the price of the stay according to aankomstDatum and vertrekDatum, so it's correct I still have to convert the vars to dates? I did it with the following code starting from dd-mm-yy:
var parts = aankomstDatum.split('-');
var aankomstDatumDate = new Date(parts[2],parts[0]-1,parts[1]);
document.getElementById("aankomstDate").innerHTML = aankomstDatumDate;
When I output aankomstDatumDate I get a working date in the following format: Sat Nov 11 2017 00:00:00 GMT+0100 (Romance Standard Time).
My two questions:
1) Is this step necessary? Is my train of thought correct that I start with dates and convert them to dates first before I can use them to calculate a booking price?
2) Is the outputted date Sat Nov 11 2017 00:00:00 GMT+0100 (Romance Standard Time) okay to use to calculate the booking price? Or is it way better to have it in a format like "dd-mm-yy"? And if so, how do I achieve that?
Answering your two questions:
Date
objects so that you can do operations on those dates. getTime()
on those dates, which returns the dates in Unix Time (milliseconds). For example, if you wanted to calculate the number of days that a user was checked in for (checkoutDate - checkinDate), you would use this function, which accepts two date objects:
function daysDifference(date1, date2) {
let diff = date2.getTime() - date1.getTime();
return Math.round(diff / (1000*60*60*24)); // divide by number of milliseconds in a day
}
// Example
var date1 = new Date(); // today
var date2 = new Date();
// add 5 days to date2
date2.setDate(date2.getDate() + 5);
var daysCheckedIn = daysDifference(date1, date2);
console.log("User checked in for: " + daysCheckedIn + " days.");