如何将javascript中的日期格式化为DD-MMM-YYYY?
因此后端为FE提供的日期为:'2019-05-30T00:00:00.000Z' 我正在尝试将FE渲染为2019年5月30日 所以 我一直在尝试使用如何将javascript中的日期格式化为DD-MMM-YYYY?,javascript,date,datetime-format,Javascript,Date,Datetime Format,因此后端为FE提供的日期为:'2019-05-30T00:00:00.000Z' 我正在尝试将FE渲染为2019年5月30日 所以 我一直在尝试使用 但是,您如何开始将日期对象和控件修改为所需的输出呢?这使用toLocaleString()方法来获取月份名称,否则您将需要一个月名称数组来匹配Date.getMonth()的输出,它将只是一个数字(0索引)(例如,一月将是0) let date=新日期(date.parse('2012-01-26T13:51:50.417-07:00'); lo
但是,您如何开始将日期对象和控件修改为所需的输出呢?这使用
toLocaleString()
方法来获取月份名称,否则您将需要一个月名称数组来匹配Date.getMonth()
的输出,它将只是一个数字(0索引)(例如,一月将是0)
let date=新日期(date.parse('2012-01-26T13:51:50.417-07:00');
log(`date.getDate()}-${date.toLocaleString('default',{month:'long'})}-${date.getFullYear()}`)代码>
预定义函数和数组。感谢您对这个问题的所有贡献
我设法为此创建了一个工作函数:
formatDate(value) {
let date = new Date(value);
const day = date.toLocaleString('default', { day: '2-digit' });
const month = date.toLocaleString('default', { month: 'short' });
const year = date.toLocaleString('default', { year: 'numeric' });
return day + '-' + month + '-' + year;
}
您不需要修改日期对象,而是使用它必须输出您想要的内容的方法(提示:.getDate
,.getMonth
,.getFullyear
)@JaromandaX-Ahh得到了您的支持,因此可以像您所说的那样使用.getDate、.getMonth、.getFullyear来构建所需的输出。Brilliant mate:)或者,如果你喜欢冒险,你可以使用合适的区域设置和选项。有大量问题,请尝试编写自己的代码,然后询问是否有问题。在new Date(Date.parse(string))
中使用Date.parse是多余的,new Date(string)
将产生相同的结果。您是否听说过Array.prototype.indexOf()
?这与。
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
month = monthNames[date.getMonth()];
function formatDate(dateString) {
let date = new Date(dateString),
day = date.getDay(),
month = date.getMonth(),
year = date.getFullYear(),
months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
return day + '-' + months[month] + '-' + year;
}
formatDate(value) {
let date = new Date(value);
const day = date.toLocaleString('default', { day: '2-digit' });
const month = date.toLocaleString('default', { month: 'short' });
const year = date.toLocaleString('default', { year: 'numeric' });
return day + '-' + month + '-' + year;
}