在 JavaScript 中格式化 DateTimes 的一种有用且灵活的方法是 Intl.DateTimeFormat:
var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));
结果是:"12-Oct-2017"
可以使用 options 参数自定义日期和时间格式。
Intl.DateTimeFormat 对象是启用语言敏感日期和时间格式的对象的构造函数。
语法
new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
参数
地区
可选。带有 BCP 47 语言标记的字符串,或此类字符串的数组。有关 locales 参数的一般形式和解释,请参阅 Intl 页面。允许使用以下 Unicode 扩展键:
nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".
选项
可选。具有以下部分或全部属性的对象:
localeMatcher
要使用的语言环境匹配算法。可能的值为"lookup" 和"best fit";默认为"best fit"。有关此选项的信息,请参阅 Intl 页面。
时区
要使用的时区。实现必须识别的唯一值是"UTC";默认值是运行时的默认时区。实现还可以识别 IANA 时区数据库的时区名称,例如 "Asia/Shanghai"、"Asia/Kolkata"、"America/New_York"。
12 小时
是否使用 12 小时制(而不是 24 小时制)。可能的值为true 和false;默认值取决于区域设置。
格式匹配器
要使用的格式匹配算法。可能的值为"basic" 和"best fit";默认为"best fit"。有关使用此属性的信息,请参阅以下段落。
以下属性描述了在格式化输出中使用的日期时间组件及其所需的表示形式。实现需要至少支持以下子集:
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
实现可能支持其他子集,并且将针对所有可用的子集表示组合协商请求以找到最佳匹配。两种算法可用于此协商并由 formatMatcher 属性选择:完全指定的"basic" 算法和依赖于实现的“最佳拟合”算法。
工作日
工作日的表示。可能的值为"narrow"、"short"、"long"。
时代
时代的代表。可能的值为"narrow"、"short"、"long"。
年份
年份的表示。可能的值为"numeric"、"2-digit"。
月
月份的表示。可能的值为"numeric"、"2-digit"、"narrow"、"short"、"long"。
一天
当天的表现。可能的值为"numeric"、"2-digit"。
小时
小时的表示。可能的值为"numeric"、"2-digit"。
分钟
分钟的表示。可能的值为"numeric"、"2-digit"。
秒
第二个的表示。可能的值为"numeric"、"2-digit"。
时区名称
时区名称的表示。可能的值为"short"、"long"。
每个日期时间组件属性的默认值未定义,但如果所有组件属性未定义,则假定年、月和日为"numeric"。
Check Online
More Details