JavaScript 中的 Date
对象用于处理日期和时间。日期格式转换是将 Date
对象转换为特定格式的字符串,或者将特定格式的字符串转换为 Date
对象的过程。
常见的日期格式包括:
YYYY-MM-DD
MM/DD/YYYY
DD-MM-YYYY
YYYY年MM月DD日
function formatDate(date, format) {
const map = {
'M': date.getMonth() + 1, // 月份从 0 开始
'd': date.getDate(),
'h': date.getHours(),
'm': date.getMinutes(),
's': date.getSeconds(),
'q': Math.floor((date.getMonth() + 3) / 3), // 季度
'S': date.getMilliseconds() // 毫秒
};
format = format.replace(/([yMdhmsqS])+/g, (all, t) => {
let v = map[t];
if (v !== undefined) {
if (all.length > 1) {
v = '0' + v;
v = v.substr(v.length - 2);
}
return v;
} else if (t === 'y') {
return (date.getFullYear() + '').substr(4 - all.length);
}
return all;
});
return format;
}
const date = new Date();
console.log(formatDate(date, 'YYYY-MM-DD')); // 输出类似 2023-04-10
console.log(formatDate(date, 'MM/DD/YYYY')); // 输出类似 04/10/2023
function parseDate(dateStr, format) {
const parts = dateStr.match(/(\d+)/g);
const formatParts = format.match(/([yMdhmsqS])/g);
const map = {
'M': 1,
'd': 2,
'h': 3,
'm': 4,
's': 5,
'q': 6,
'S': 7
};
const dateObj = new Date();
for (let i = 0; i < formatParts.length; i++) {
const part = formatParts[i];
const value = parseInt(parts[i], 10);
switch (part) {
case 'y':
dateObj.setFullYear(value);
break;
case 'M':
dateObj.setMonth(value - 1);
break;
case 'd':
dateObj.setDate(value);
break;
case 'h':
dateObj.setHours(value);
break;
case 'm':
dateObj.setMinutes(value);
break;
case 's':
dateObj.setSeconds(value);
break;
case 'q':
dateObj.setMonth((value - 1) * 3);
break;
case 'S':
dateObj.setMilliseconds(value);
break;
}
}
return dateObj;
}
const dateStr = '2023-04-10';
const dateObj = parseDate(dateStr, 'YYYY-MM-DD');
console.log(dateObj); // 输出类似 Tue Apr 10 2023 00:00:00 GMT+0800 (中国标准时间)
原因:
解决方法:
isNaN(date.getTime())
来验证。if (isNaN(date.getTime())) {
console.error('Invalid date object');
return;
}
原因:
解决方法:
const regex = /^\d{4}-\d{2}-\d{2}$/;
if (!regex.test(dateStr)) {
console.error('Invalid date string format');
return;
}
通过以上方法,可以有效处理 JavaScript 中的日期格式转换问题。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云