Date对象提供了三个格式化本地时时间的函数
Date.prototype.toLocaleString
Date.prototype.toLocaleDateString
Date.prototype.toLocaleTimeString
可通过转入国家代码获取相应的本地化时间,比如中国为zh-CN
new Date().toLocaleString('zh-CN')
//输出: '2022/9/29 16:14:48'
其它示例
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Formats below assume the local time zone of the locale;
// America/Los_Angeles for the US
// US English uses month-day-year order and 12-hour time with AM/PM
console.log(date.toLocaleString('en-US'));
// → "12/19/2012, 7:00:00 PM"
// British English uses day-month-year order and 24-hour time without AM/PM
console.log(date.toLocaleString('en-GB'));
// → "20/12/2012 03:00:00"
// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(date.toLocaleString('ko-KR'));
// → "2012. 12. 20. 오후 12:00:00"
// Arabic in most Arabic-speaking countries uses Eastern Arabic numerals
console.log(date.toLocaleString('ar-EG'));
// → "٢٠/١٢/٢٠١٢ ٥:٠٠:٠٠ ص"
// For Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleString('ja-JP-u-ca-japanese'));
// → "24/12/20 12:00:00"
// When requesting a language that may not be supported, such as
// Balinese, include a fallback language (in this case, Indonesian)
console.log(date.toLocaleString(['ban', 'id']));
// → "20/12/2012 11.00.00"
自定义日期格式
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Request a weekday along with a long date
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
};
console.log(date.toLocaleString('de-DE', options));
// → "Donnerstag, 20. Dezember 2012"
回复 (0)
微信扫码 立即评论