javascript - Opposite method to toLocaleDateString -


in order create string respects browser culture, can do:

var mydate = new date(); var mydatestring = mydate.tolocaledatestring(mydate); //returns string 

which nice, because if i'm in portugal, 1st of june, output "01/06/2015", while if i'm on states, output "06/01/2015".

now want exact opposite. want:

var mydatestring = "01/06/2015" var mydate = mydatestring.tolocaledate(); //it should return date 

any suggestions?

browsers have no idea "culture" user identifies with, has access regional settings various formatted strings (date, number, currency, language, etc.). there no standard javascript api access these settings.

browsers have access regional settings, don't reliably implement particular formatting date.prototype.tolocalestring, it's impossible reliably translate date string date object based on browser's interpretation of system settings. lastly, there's no guarantee arbitrary date string conform regional settings anyway.

the reliable way parse string specify particular format. if you've specified d/m/y , user enters 1/6/2015, have no options trust have read , understood required format , intend interpreted 1 june 2015. there no other option.

parsing date of particular format not difficult, e.g. parse 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 line required if date 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 want ensure 2 digit years treated full years (most browsers convert, say, 1/1/03 1/1/1903), 1 more line 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); } 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -