Search code examples
javascriptdatedatetimetype-conversionvar

Are these vars converted to date correctly to use them for booking price calculations?


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?


Solution

  • Answering your two questions:

    1. Yes, this train of thought is correct -- you want to convert your strings into Date objects so that you can do operations on those dates.
    2. If you are planning on using some sort of arithmetic on the dates, you probably want to use 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.");