JavaScript 将日期格式 2006年10月31日 转换为 2006-10-31
你可以使用 JavaScript 的 Date 对象来实现这个方法,具体代码如下:
function formatDate(dateString) {
// 将日期字符串转换为 Date 对象
let date = new Date(dateString);
// 获取年、月、日
let year = date.getFullYear();
let month = String(date.getMonth() + 1).padStart(2, '0');
let day = String(date.getDate()).padStart(2, '0');
// 返回格式化后的日期字符串
return `${year}-${month}-${day}`;
}
// 示例用法
let dateString = '2006年10月31日';
let formattedDate = formatDate(dateString);
console.log(formattedDate); // 输出: 2006-10-31
在这个方法中,我们首先创建一个新的 Date 对象,将日期字符串作为参数传递给它。然后,我们使用 Date 对象的方法来获取年、月和日,并将它们格式化为我们想要的字符串格式(例如,'2006-10-31')。最后,我们返回格式化后的日期字符串。
原文地址: https://www.cveoy.top/t/topic/pVk0 著作权归作者所有。请勿转载和采集!