Opposite method to toLocaleDateString

3.4k views Asked by At

In order to create a string that respects the browser culture, we can do:

var myDate = new Date();
var myDateString = myDate.toLocaleDateString(myDate); //returns a string

Which is nice, because if I'm in Portugal, for the 1st of June, this will output "01/06/2015", while if I'm on the states, it will output "06/01/2015".

Now I want the exact opposite. I want:

var myDateString = "01/06/2015"
var myDate = myDateString.toLocaleDate(); //it should return a Date

Any suggestions?

1

There are 1 answers

0
RobG On BEST ANSWER

Browsers have no idea what "culture" a user identifies with, it only has access to regional settings for various formatted strings (date, number, currency, language, etc.). There is no standard javascript API to access these settings.

Browsers do have access to regional settings, however they don't reliably implement any particular formatting for Date.prototype.toLocaleString, so it's impossible to reliably translate a Date string to a Date object based on the browser's interpretation of system settings. Lastly, there's no guarantee that any arbitrary date string will conform to regional settings anyway.

The only reliable way to parse a string is to specify a particular format. If you've specified d/m/y and the user enters 1/6/2015, you have no options but to trust that they have read and understood the required format and intend it to be interpreted as 1 June 2015. There really is no other option.

Parsing a date of a particular format is not difficult, e.g. to parse a string in d/m/y format:

function parseDMY(s) {
  var b = s.split(/\D+/);
  return new Date(b[2], b[1]-1, b[0]);
}

An extra line is required if the date is to be validated:

function parseDMY(s) {
  var b = s.split(/\D+/);
  var d = new Date(b[2], b[1]-1, b[0]);
  return d && d.getMonth() == b[1]-1? d : new Date(NaN);
}

If you want to ensure that 2 digit years are treated as full years (most browsers will convert, say, 1/1/03 to 1/1/1903), then one more line is required:

function parseDMY(s) {
  var b = s.split(/\D+/);
  var d = new Date(b[2], b[1]-1, b[0]);
  d.setFullYear(b[2]);
  return d && d.getMonth() == b[1]-1? d : new Date(NaN);
}