如何将含时区偏移的日期字符串转换为指定格式?
日期字符串解析与格式化解决方案
问题原因
你提供的日期字符串"2020-09-09T12:41:41 -04:00"不符合ISO 8601标准格式——时区偏移-04:00前多了一个空格,这直接导致new Date()无法识别,返回Invalid Date。
实现步骤
1. 修复日期字符串
先移除时区偏移前的空格,让Date对象能正确解析:
const originalDateStr = "2020-09-09T12:41:41 -04:00"; // 移除时间部分与时区之间的空格 const fixedDateStr = originalDateStr.replace(/(\d{2}:\d{2}:\d{2}) /, "$1"); const date = new Date(fixedDateStr);
2. 格式化为目标样式
有两种可靠方式实现"MM/DD/YYYY, h:mm:ss PM"格式:
方式一:手动拼接格式化
手动提取并处理日期时间各部分,精准控制格式:
function formatTargetDate(date) { const month = date.getMonth() + 1; // 月份从0开始,需加1 const day = date.getDate(); const year = date.getFullYear(); let hours = date.getHours(); const period = hours >= 12 ? "PM" : "AM"; hours = hours % 12 || 12; // 把0点转为12点,适配12小时制 // 补零处理分钟、秒 const minutes = String(date.getMinutes()).padStart(2, "0"); const seconds = String(date.getSeconds()).padStart(2, "0"); return `${month}/${day}/${year}, ${hours}:${minutes}:${seconds} ${period}`; } // 使用示例 const formattedDate = formatTargetDate(date); console.log(formattedDate); // 输出 "9/9/2020, 12:41:41 PM"
方式二:使用原生Intl.DateTimeFormat
利用浏览器原生API简化格式化逻辑:
const formatter = new Intl.DateTimeFormat("en-US", { year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "2-digit", second: "2-digit", hour12: true }); // 调整逗号后空格,匹配目标格式 const formattedDate = formatter.format(date).replace(",", ", "); console.log(formattedDate); // 输出 "9/9/2020, 12:41:41 PM"
完整可运行代码
const originalDateStr = "2020-09-09T12:41:41 -04:00"; const fixedDateStr = originalDateStr.replace(/(\d{2}:\d{2}:\d{2}) /, "$1"); const date = new Date(fixedDateStr); function formatTargetDate(date) { const month = date.getMonth() + 1; const day = date.getDate(); const year = date.getFullYear(); let hours = date.getHours(); const period = hours >= 12 ? "PM" : "AM"; hours = hours % 12 || 12; const minutes = String(date.getMinutes()).padStart(2, "0"); const seconds = String(date.getSeconds()).padStart(2, "0"); return `${month}/${day}/${year}, ${hours}:${minutes}:${seconds} ${period}`; } console.log(formatTargetDate(date));
内容的提问来源于stack exchange,提问作者Ivan Dimov
相关产品推荐
相关产品推荐

