如何解决本地客户端 JavaScript 数字日期格式在浏览器中
因此,对于如何在特定于用户语言环境的客户端 JavaScript 中获取数字日期格式,我找不到好的答案。例如。如果您的语言是“en-US”,我希望得到“MM/DD/YYYY”。
解决方法
Date.toLocaleDateString
可以通过 options {year: 'numeric',month: '2-digit',day: '2-digit',}
以最接近用户语言环境的数字格式来格式化日期。
要获得带有“YYYY”、“MM”和“DD”占位符的日期格式,您可以用相应的占位符字符串替换特定的年、月和日。
// Replace with date format e.g. 'MM/DD/YYYY'
const FALLBACK_DATE_FORMAT = 'your fallback date format';
// Memoize return value
let cachedNumericFixedWidthDateFormat = null;
function getNumericFixedWidthDateFormat() {
if (cachedNumericFixedWidthDateFormat !== null) {
return cachedNumericFixedWidthDateFormat;
}
let dateFormat;
try {
const dummyDate = new Date();
dummyDate.setFullYear(1984);
dummyDate.setMonth(0);
dummyDate.setDate(23);
dateFormat = dummyDate.toLocaleDateString(undefined,{
year: 'numeric',}).replace('1984','YYYY').replace('01','MM').replace('23','DD');
} catch (err) {
// TODO: Monitor errors!
return FALLBACK_DATE_FORMAT;
}
if (checkIsValidDateFormat(dateFormat)) {
cachedNumericFixedWidthDateFormat = dateFormat;
return dateFormat;
} else {
// TODO: Add monitoring!
return FALLBACK_DATE_FORMAT;
}
}
function checkIsValidDateFormat(dateFormat) {
const yearCharsMatches = dateFormat.match(/YYYY/g);
const monthCharsMatches = dateFormat.match(/MM/g);
const dayCharsMatches = dateFormat.match(/DD/g);
const digitCharMatches = dateFormat.match(/[0-9]/g);
return yearCharsMatches !== null && yearCharsMatches.length === 1
&& monthCharsMatches !== null && monthCharsMatches.length === 1
&& dayCharsMatches !== null && dayCharsMatches.length === 1
&& digitCharMatches === null;
}
// Output for Mozilla Firefox 87.0 on Ubuntu 20.04:
// en-US: 'MM/DD/YYYY'
// de-DE: 'DD.MM.YYYY'
// es-ES,es-AR,en-GB: 'DD/MM/YYYY'
console.log(getNumericFixedWidthDateFormat());
虽然很难确定用户的语言环境,但我们可以确定用户的首选语言并将这些语言传递给 Intl.DateTimeFormat()
构造函数以创建日期格式化程序。
将 Date
对象传递给格式化程序的 format
函数以将日期格式化为预先指定的条件。
// Function that returns an instance of the DateTimeFormat constructor.
const createDateFormatter = () => new Intl.DateTimeFormat([],{
year: '2-digit',day: '2-digit'
});
// Current date of today.
const date = new Date();
// Create a new formatter.
const dateFormatter = createDateFormatter();
// Format the date.
const formattedDate = dateFormatter.format(date);
console.log(formattedDate);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。