我正在尝试使用 vanilla Javascript 显示日期和时间。我想显示带有用户时区的完整日期和时间。
这是我想要的输出:
Wednesday, January 30th 2019 at 08:48:47 AM PST
这是我目前所拥有的:
var date = new Date();
var n = date.toDateString();
var time = date.toLocaleTimeString();
document.getElementById('time').innerHTML = n + ' at ' + time;
<div id="time"></div>
所以我很接近。我现在需要的是将日期和月份名称扩展为全名,将 st
/rd
/th
添加到日期并附加用户的时区到最后。
最佳答案
此解决方案使用 Intl.DateTimeFormat()
以便我们可以利用 FormatToParts()
函数然后应用自定义 map()
然后最后 reduce()
得到想要的输出。
在 map()
函数中,我们将日期后缀附加到输出“st”、“nd”、“rd”和“th”。例如。第一,第二,第三,第四。后缀附加到日期本身,而不是相应的 literal
键,因为我们需要知道日期的值,所以这是最简单的方法。
在我们替换 literal
的值的地方,主要是为了删除多余的逗号(默认情况下存在),并在时间之前显示 at
。
MDN 中的引用资料:
- > DateTimeFormat
- > Date Format Options
- > Locales Argument -- 我们正在使用
undefined
以使用用户的默认值 - > FormatToParts
const d = new Date();
const formatOptions = {
weekday: 'long', month: 'long', day: 'numeric', hour: 'numeric',
minute: 'numeric', year: 'numeric', timeZoneName: 'short', hour12: true
};
// Using Intl.DateTimeFormat so we have access to
// formatToParts function which produces
// an Array of objects containing the formatted date in parts
const dateFormat = new Intl.DateTimeFormat(undefined, formatOptions);
// Keep track of 'literal' key counts (`literal` is the separator)
let separatorIndex = 0;
// Where the magic happens using map() and reduce()
const dateString = dateFormat.formatToParts(d).map(({type, value}) => {
switch (type) {
case 'literal' :
separatorIndex++;
switch (separatorIndex) {
case 3 : // Day separator
return ' ';
break;
case 4 : // Year separator
return ' at ';
default: return value;
}
break;
case 'day' :
// Append appropriate suffix
switch (value) {
case (value.slice(-1) === 1) :
return value.concat('st');
break;
case (value.slice(-1) === 2) :
return value.concat('nd');
break;
case (value.slice(-1) === 3) :
return value.concat('rd');
break;
default: return value.concat('th');
}
break;
case 'hour' :
// Prepend 0 when less than 10 o'clock
return (value < 10) ? '0'.concat(value) : value;
break;
default: return value;
}
}).reduce((string, part) => {
return string.concat(part)
});
// Not part of answer; only for output result
document.write(dateString);
关于javascript - 如何使用用户的时区获取完整的时间和日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54446203/