【问题标题】:how to determine year, month, day ordering based on locale?如何根据语言环境确定年、月、日排序?
【发布时间】:2018-07-20 00:49:20
【问题描述】:

我想显示三个自定义下拉菜单,供用户选择身份证的年月日。

如何仅使用 JavaScript(而不是 moment)来确定显示年、月和日的顺序?

en-US 的示例输出:

['month', 'day', 'year']

en-CA 的示例输出:

['year', 'month', 'day']

【问题讨论】:

  • 最好使用明确的格式,例如使用短月份名称。特定地区的人们并不总是使用相同的 Oder 值,例如有些地方可能会使用“2018 年 1 月 21 日”作为正式日期(如英国报纸),但简称 21/1/2018。
  • @RobG 我使用的是短月份名称。问题的关键在于确定以何种顺序显示年、月和日下拉菜单。月份下拉菜单包含简短的月份名称。

标签: javascript date internationalization


【解决方案1】:

function datePartOrder(locale) {
  const parts = new Intl.DateTimeFormat(locale).formatToParts();
  const filteredParts = parts.filter(part => ['year', 'month', 'day'].includes(part.type));
  const filteredPartNames = filteredParts.map(part => part.type);
  return filteredPartNames;
}

// examples:

console.log(datePartOrder('en-US')); //["month", "day", "year"] );
console.log(datePartOrder('en-CA')); //["year", "month", "day"]

【讨论】:

  • 很酷,但是 OP 如何知道要使用哪种语言标签?对我来说,省略语言会在某些浏览器中生成错误的序列(即,它与我的系统设置不一致)。
猜你喜欢
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 2015-05-22
  • 1970-01-01
相关资源
最近更新 更多