JavaScript Date Calculator - Calculation Functions


Welcome back, everyone! As I mentioned in my last post, I'm creating a Date Calculator for my JavaScript project. My first task is to the create the three main functions that will calculate the results for the users; Days Until, Days Between and Add/Subtract Days.

Add/Subtract Days

I started with Add/Subtract Days since I could combine both calculators into one function based on the radio button selected. I will code my radio buttons with values (0-3), like an index, so if the user selects Add the value of 2 will be passed into the function, and 3 will be passed in with Subtract.

I named my function incrementDays with parameters (dateString, incrementDayNum, operationType). It outputs the date you get from adding or subtracting that number of days from the selected date into a text field.
  • dateString - The date the user selects from the Calendar, passed as a String ('April 8, 2017')
  • incrementDayNum - The integer entered into the text box, passed as a String ('7').
  • operationType - The radio button value (Add = 2, Subtract = 3).

incrementDays Syntax

//operation type is determined by radio button (2 = add, 3 = subtract)
function incrementDays(dateString, incrementDayNum, operationType) {
    //check for user input in calendar and text box
    if(dateString !== 'January 1, 1970 00:00:00' && incrementDayNum !== null) {
        let incrementAmt;
        let startDate = new Date(dateString);
        let operationText;
        let toFromText;
        let resultDate = new Date(dateString);
        let resultText;
        
        //if adding (type 2), increment is parsed as a positive. 
        //else subtracting (type 3), increment is parsed as a negative.
        if(operationType === 2) {
            //convert the input days text to Float
            incrementAmt = parseFloat(incrementDayNum);
            operationText = "Adding";
            
            //grammar change for 1 vs multiple days
            if(incrementAmt !== 1 ) {
                toFromText = " days to ";
                
            }
            else {
                toFromText = " day to ";
            }
        }
        else {
            incrementAmt = -1 * parseFloat(incrementDayNum);
            operationText = "Subtracting";
            
            //grammar change for 1 vs multiple days
            if(incrementAmt !== 1) {
                toFromText = " days from ";
            }
            else {
                toFromText = " day from ";
            }
        }
        resultDate.setDate(startDate.getDate() + incrementAmt);
        resultText = operationText + " " + incrementDayNum + toFromText +
                startDate.toDateString() + " equals " + 
                resultDate.toDateString();
        document.getElementById("resultText").innerHTML = resultText;
    }
    else {
        document.getElementById("warningText").innerHTML = 
                         "Please select a date and" +
                         "enter the number of days to add or substract";
    }
}

incrementDays Example

I tested multiple inputs in the function using JSBin.com to make sure it works, and then wired up the Calculate button to call the function with specific inputs to ensure it would output correctly in the textResult HTML element.

Days Until Function

The daysUntil function takes a single parameter, dateString, that must be a future date from today. The function will output the number of days, from today, until that future date into a text field.

I had to use the getTime() method to get the date in milliseconds from January 1, 1970 UTC, aka "epoch date" or the date when time started for Unix computers. It is the minimum value of time from which future dates are calculated. By doing this I had to convert the result of my subtraction back to days incorporating the Math.ceil function to round up because the today date includes a time stamp from when the user hits the calculate button, resulting in a partial day.

daysUntil Syntax 

function daysUntil (dateString) {
    let today = new Date();
    let futureDate = new Date(dateString);
    let numDaysUntil;
    let resultText;

    //checks that the date selected is in the future
    if (futureDate > today) {

        //converts the dates into milliseconds, subtracts 
        //and converts back to days
        numDaysUntil = Math.ceil(futureDate.getTime() - today.getTime();
        numDaysUntil = numDaysUntil/(1000 * 60 * 60 * 24));

        //grammar check for 1 vs multiple days        
        if (numDaysUntil === 1) {
            resultText = "There is " +
                    numDaysUntil + 
                    " day from today, " +
                    today.toDateString() +
                    ", until " +
                    futureDate.toDateString();
        }
        else {
            resultText = "There are " +
                    numDaysUntil + 
                    " days from today, " +
                    today.toDateString() +
                    ", until " +
                    futureDate.toDateString();
        }
        document.getElementById("resultText").innerHTML = resultText; 
 
    }
    else {
        document.getElementById("warningText").innerHTML =
                                "Please select a date in the future";
    }
}

daysUntil Example

Like the first example, I tested multiple inputs to ensure that the code works. I made sure to include past dates to make sure the warning text works. Then, I tested the function using the Calculate button to make sure it would output to the HTML text field.

Days Between Function

To calculate the number of days between two dates I wrote the daysBetween function that takes two parameters, both dateStrings. This function outputs the number of days between the two dates into a text field.

Again, I had to use the getTime method and convert the difference between the dates into days using rounding, though this time I used Math.floor since both dates have the same time stamp. Also, since the first date selected could be after the second date, I used Math.abs to get the absolute value, ensuring that the result would always be positive.

daysBetween Syntax

function daysBetween (dateString1, dateString2) {
    let date1 = new Date(dateString1);
    let date2 = new Date(dateString2);
    let dateDifference;
    let resultText;
    
    //checking to make sure user selected two dates
    if(dateString1 !== 'January 1, 1970' && dateString2 !== 'January 1, 1970') {
        
        //use absolute value to make sure difference is always positive
        dateDifference = Math.abs(date1.getTime() - date2.getTime());
        
        //convert from milliseconds to days
        dateDifference = Math.floor(dateDifference/(1000 * 60 * 60 * 24));
        
        //grammar check for 1 vs multiple days
        if(dateDifference ===1) {
            resultText = "There is " +
                    dateDifference +
                    " day between " +
                    date1.toDateString() +
                    " and " +
                    date2.toDateString();
        }
        else {
            resultText = "There are " +
                    dateDifference +
                    " days between " +
                    date1.toDateString() +
                    " and " +
                    date2.toDateString();
        }
        document.getElementById("resultText").innerHTML = resultText;
    }
    else {
        document.getElementById("warningText").innerHTML = 
                       "Please select a date on both calendars";
    }
    
}

daysBetween Example

Again, I tested multiple inputs to make sure that the code runs correctly and then wired it up to my calculate button to test that it outputs correctly.

That's it for this week. I know this is a LOT of code to look through, so if you have any questions, send them my way! Next week, I'll be tackling the calendar inputs.

Comments