Brandon Brandon - 3 months ago 27
Javascript Question

How to get 2 digit year w/ Javascript?

I am trying to find some javascript code that will write the current date in this format: mmddyy

Everything I have found uses 4 digit years and I need 2 digit.

Answer

The specific answer to this question is found in these two lines below:

//pull the last two digits of the year
alert(new Date().getFullYear().toString().substr(2,2));

Formatting Full Date Time Example (MMddyy): jsFiddle

JS:

//A function for formatting a date to MMddyy
function formatDate(d)
{
    //get the month
    var month = d.getMonth();
    //get the day
    var day = d.getDate();
    //get the year
    var year = d.getFullYear();

    //pull the last two digits of the year
    year = year.toString().substr(2,2);

    //increment month by 1 since it is 0 indexed
    month = month + 1;
    //converts month to a string
    month = month + "";

    //if month is 1-9 pad right with a 0 for two digits
    if (month.length == 1)
    {
        month = "0" + month;
    }

    //convert day to string
    day = day + "";

    //if day is between 1-9 pad right with a 0 for two digits
    if (day.length == 1)
    {
        day = "0" + day;
    }

    //return the string "MMddyy"
    return month + day + year;
}

var d = new Date();
alert(formatDate(d));
Comments