4

Possible Duplicate:
JavaScript date objects UK dates

I have the following code and I am having problem setting the date format to british i.e

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's 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.
Community
  • 1
  • 1
user1960982
  • 39
  • 1
  • 2

2 Answers2

3

JavaScript now supports dates in ISO8601 format, it is beneficial to use standardised formats wherever possible - you'll experience far fewer compatibility issues:

var birthday = new Date("1988-09-20");
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
2

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

I would recommend you to parse your date string manually, and use the Date constructor with the year, month and day arguments to avoid ambiguity

You can create your own parse method for your date format like this (from 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]);
}
Community
  • 1
  • 1
German Latorre
  • 10,058
  • 14
  • 48
  • 59