How do I change the date format to imperial in JavaScript?

Possible duplicate:
UK date date objects.

I have the following code and I have a problem setting the date format to British ie

var birthday = new Date("20/9/1988"); 

      

when i run the code i get You are NaN years old

. error, but if I change it to say 09 / 20.1988 it works

var birthday = new Date("20/9/1988");
var today = new Date();
var years = today.getFullYear() - birthday.getFullYear();

// Reset birthday to the current year.
birthday.setFullYear(today.getFullYear());

// If the user birthday has not occurred yet this year, subtract 1.
if (today < birthday)
{
    years--;
}
document.write("You are " + years + " years old.");

// Output: You are years years old.

      

+3


source to share


2 answers


JavaScript now supports ISO8601 dates , it is beneficial to use standardized formats wherever possible - you will have much less compatibility issues:



var birthday = new Date("1988-09-20");

      

+3


source


One option is the one described in the question Why Date.parse gives incorrect results? :

I would recommend that you manually parse the date string and use the Date Constructor with year, month and day arguments to avoid Ambiguity



You can create your own syntax method for date format like this (from the question Why does Date.parse give incorrect results? ):

// Parse date in dd/mm/yyyy format
function parseDate(input)
{
    // Split the date, divider is '/'
    var parts = input.match(/(\d+)/g);

    // Build date (months are 0-based)
    return new Date(parts[2], parts[1]-1, parts[0]);
}

      

+2


source