与toLocaleDateString相反的方法 [英] Opposite method to toLocaleDateString

查看:187
本文介绍了与toLocaleDateString相反的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了创建一个尊重浏览器文化的字符串,我们可以这样做:

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

这很好,因为如果我在葡萄牙在6月1日,它将输出"01/06/2015",而如果我在各州,则将输出"06/01/2015" .

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

有什么建议吗?

推荐答案

浏览器不知道用户识别的是哪种文化",它只能访问各种格式的字符串(日期,数字,货币,语言, ETC.).没有标准的JavaScript API可以访问这些设置.

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.

浏览器可以访问区域设置,但是它们无法可靠地实现 Date.prototype.toLocaleString 的任何特定格式,因此无法根据以下内容可靠地将Date字符串转换为Date对象:浏览器对系统设置的解释.最后,我们无法保证任何日期字符串都符合区域设置.

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.

解析字符串的唯一可靠方法是指定特定格式.如果您指定d/m/y并且用户输入1/6/2015,那么您别无选择,只能相信他们已经阅读并理解了所需的格式,并希望将其解释为2015年6月1日.没有其他选择.

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.

解析特定格式的日期并不困难,例如解析d/m/y格式的字符串:

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);
}

如果要确保将两位数的年份视为完整年份(大多数浏览器会将1/1/03转换为1/1/1903),则需要再增加一行:

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);
}

这篇关于与toLocaleDateString相反的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆