我如何在外部Java脚本文件中写一个像这样的日期2019年2月13日星期三?
答案 0 :(得分:1)
function formatDate(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var dayofweek=[
"Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
var dowIdx = date.getDay();
return( dayofweek[dowIdx] + ', ' + monthNames[monthIndex] + ' ' +day + " " + year);
}
console.log(formatDate(new Date()));
答案 1 :(得分:0)
此解决方案使用Intl.DateTimeFormat()
,因此我们可以利用FormatToParts()
函数,然后应用自定义map()
,最后是reduce()
,以获得所需的输出。
在map()
函数中,我们将day值后的literal
的值替换为逗号(默认为逗号)。
在MDN上的引用:
undefined
来使用用户的默认值
const d = new Date();
const formatOptions = {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
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 ' ';
default: return value;
}
break;
default: return value;
}
})
.reduce((string, part) => {
return string.concat(part)
});
// Not part of answer; only for output result
document.write(dateString);