Opposite method to toLocaleDateString

元气小坏坏 提交于 2019-12-04 20:07:45

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!