Home Page
Blog

Date Parsing, Addition and Display in Javascript

Google

Introduction

There are lots of sites that describe various ways of dealing with dates in javascript, but all I wanted was a simple way to read a date that the user had typed in, subtract a day, and then display this back to the user. I couldn't find anything, so I wrote this one. This version is the object oriented version, using prototypes.

Start Date: US Format (mm/dd/yyyy)
Date +n: UK Format (dd/mm/yyyy)

Days To Add:
Use negative numbers (e.g. -5) to subtract days

The Code

<script type="text/javascript">

    Date.prototype.usFormat = false;

    function Date_Parse(txtDate, usFormat)
    {
        var dateParts = txtDate.split(/[^0-9]+/);

        var year = Number(dateParts[2]);
        if (year < 50)  // so 0-49 becomes 2000-2049, 50-99 become 1950-1999 
            year += 2000;
        else if (year < 100)
            year += 1900;
        var unixDate;
        if (usFormat)
            unixDate = new Date(year.toString(), dateParts[0]-1, dateParts[1]);
        else
            unixDate = new Date(year.toString(), dateParts[1]-1, dateParts[0]);
        unixDate.usFormat = usFormat;
        return unixDate;
    }
    
    Date.prototype.AddDays = function(days)
    {
        var unixDate;
        unixDate = new Date(this.getTime() + days * 24 * 60 * 60 * 1000);
        this.setFullYear(unixDate.getFullYear());
        this.setMonth(unixDate.getMonth());
        this.setDate(unixDate.getDate());
    }
    
    Date.prototype.ToString = function()
    {
        var newDay = this.getDate().toString();
        var newMonth = (this.getMonth()+1).toString();
        var newYear = this.getFullYear().toString();
        var newDateStr;
        if (this.usFormat)
            newDateStr = (newMonth + "/" + newDay + "/" + newYear);
        else
            newDateStr = (newDay + "/" + newMonth + "/" + newYear);
        return newDateStr;
    }

</script>

As an example of using this, I have the following function that is called when the "add" button is clicked:

<script type="text/javascript">

    function DoAddition()
    {
        var dateStr = document.getElementById("StartDateText").value;
        var daysToAdd = document.getElementById("DaysToAddText").value;
        var usFormat = document.getElementById("USRadio").checked;
        var dateOb = Date_Parse(dateStr, usFormat);
        dateOb.AddDays(daysToAdd);
        document.getElementById("EndDateText").value = dateOb.ToString(usFormat);
    }

</script>