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?
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:
An extra line is required if the date is to be validated:
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: