嵌入JSON Feed时如何格式化日期字符串?getDate、moment均无效
解决JSON日期字符串格式化问题
你的问题出在日期字符串的解析和格式化步骤上,以下是两种可行的解决方案:
方案一:原生JavaScript实现(无需第三方库)
现代浏览器支持通过Intl.DateTimeFormat轻松格式化日期,只需先将JSON返回的YYYY-MM-DD HH:mm:ss格式字符串正确转为Date对象(把空格替换为T可兼容所有浏览器):
document.addEventListener("DOMContentLoaded", function() { // 定义格式化函数 function formatDate(dateStr) { const date = new Date(dateStr.replace(' ', 'T')); // 生成 "Wednesday, May 8 6:00 PM" 格式 return new Intl.DateTimeFormat('en-US', { weekday: 'long', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true }).format(date); // 若需要 "05/08/2024 6:00 PM" 格式,替换为以下配置 // return new Intl.DateTimeFormat('en-US', { // month: '2-digit', // day: '2-digit', // year: 'numeric', // hour: 'numeric', // minute: 'numeric', // hour12: true // }).format(date); } fetch('jsonsource') .then((response) => response.json()) .then((json) => { console.log(json); document.getElementById("feedtitle1").innerHTML = json[0].title; document.getElementById("feeddesc1").innerHTML = json[0].description; document.getElementById("feedurl1a").href = json[0].url; document.getElementById("feedurl1b").href = json[0].url; document.getElementById("feedurl1c").href = json[0].url; // 调用格式化函数处理日期 document.getElementById("feeddate1").innerHTML = formatDate(json[0].start_date); document.getElementById("feedimage1").src = json[0].image; }) });
方案二:使用Moment.js(修正解析格式)
你之前用Moment失败大概率是因为没指定解析格式,Moment需要明确告知输入字符串的格式才能正确解析:
document.addEventListener("DOMContentLoaded", function() { // 定义格式化函数(需确保已引入Moment.js) function formatDateWithMoment(dateStr) { // 生成 "Wednesday, May 8 6:00 PM" 格式 return moment(dateStr, 'YYYY-MM-DD HH:mm:ss').format('dddd, MMMM D h:mm A'); // 若需要 "05/08/2024 6:00 PM" 格式,替换为以下代码 // return moment(dateStr, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YYYY h:mm A'); } fetch('jsonsource') .then((response) => response.json()) .then((json) => { console.log(json); document.getElementById("feedtitle1").innerHTML = json[0].title; document.getElementById("feeddesc1").innerHTML = json[0].description; document.getElementById("feedurl1a").href = json[0].url; document.getElementById("feedurl1b").href = json[0].url; document.getElementById("feedurl1c").href = json[0].url; // 调用Moment格式化函数 document.getElementById("feeddate1").innerHTML = formatDateWithMoment(json[0].start_date); document.getElementById("feedimage1").src = json[0].image; }) });
内容的提问来源于stack exchange,提问作者SR3
相关产品推荐
相关产品推荐

