繁体   English   中英

本地客户端 JavaScript 数字日期格式(在浏览器中)

[英]local client-side JavaScript numeric date format (in browser)

因此,对于如何在特定于用户区域设置的客户端 JavaScript 中获取数字日期格式,我找不到一个好的答案。 例如,如果您的语言是“en-US”,我想得到“MM/DD/YYYY”。

Date.toLocaleDateString可以通过选项{year: 'numeric', month: '2-digit', day: '2-digit',}以最接近用户区域设置的数字格式格式化日期。

要获得带有“YYYY”、“MM”和“DD”占位符的日期格式,您可以用相应的占位符字符串替换特定的年、月和日。

 // Replace with date format eg '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': month, '2-digit': day, '2-digit'. }),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());
原装 TypeScript 操场

虽然很难确定用户的语言环境,但我们可以确定用户的首选语言并将其传递给Intl.DateTimeFormat()构造函数以创建日期格式化程序。

Date object 传递给格式化程序的format function 以将日期格式化为预先指定的条件。

 // Function that returns an instance of the DateTimeFormat constructor. const createDateFormatter = () => new Intl.DateTimeFormat([], { year: '2-digit', month: '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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM