4 回答
TA贡献1895条经验 获得超7个赞
如果输入字符串总是格式良好的 ISO 8601 日期,那么使用输入字符串相当简单:
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
const reformatDate = (iso) => {
const [year, month, day] = iso.split('-')
return `${Number(day)} ${monthNames[Number(month) - 1]} ${year}`
}
console .log (
reformatDate ('1960-06-21') //~> "21 June 1960"
)
// Or to do a list of dates:
const dates = ['1865-04-15', '1881-07-02', '1901-09-19', '1963-11-22']
console .log (
dates .map (reformatDate)
//~> ["15 April 1865", "2 July 1881", "19 September 1901", "22 November 1963"]
)
TA贡献1820条经验 获得超10个赞
我会使用支持我的日期的方法:
function df(date){
const m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return date.getUTCDate()+' '+m[date.getUTCMonth()]+' '+date.getUTCFullYear();
}
const dt = new Date('1960-06-21');
console.log(df(dt));
TA贡献1874条经验 获得超12个赞
尝试:
const dt = new Date('1960-06-21');
const convert = (date) =>{
const dateArr = date.toString().split(' ')
return dateArr[2] +' '+dateArr[1] +' '+dateArr[3]
}
console.log(convert(dt))
TA贡献1772条经验 获得超6个赞
为什么你不能创建一个函数并重用它?
例子:
const dtf = new Intl.DateTimeFormat('en', {
year: 'numeric',
month: 'long',
day: '2-digit',
timeZone: 'UTC'
});
function formatDate(date, format) {
const [{ value: mo }, , { value: da }, , { value: ye }] = format.formatToParts(date);
return `${da} ${mo} ${ye}`;
}
const dates = ['1993-10-30', '2003-10-29', '1999-12-30'];
console.log(dates
.map(date => Date.parse(date))
.map(date => formatDate(date, dtf))
);
添加回答
举报