如何在JavaScript中修改日期格式?如何去除Date结果中的GMT标识?
在JavaScript中修改日期格式及移除GMT内容的方法
嘿,我来帮你搞定这两个问题!不用写冗长的解析代码,原生JS就有很多便捷的方案。
一、如何修改日期格式
JavaScript原生提供了多种灵活的日期格式化方式,完全不用自己造轮子:
1. 使用Intl.DateTimeFormat(推荐,支持多语言和自定义)
这是ES6引入的国际化API,能轻松定制各种日期格式,示例如下:
// 生成类似「YYYY-MM-DD HH:mm:ss」的格式 const date = new Date('2018-04-28T18:38:23Z'); const formatter = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false // 启用24小时制 }); // 拆分日期和时间部分,统一分隔符 const [datePart, timePart] = formatter.format(date).split(', '); const formatted = datePart.replace(/\//g, '-') + ' ' + timePart; console.log(formatted); // 输出 "04-28-2018 18:38:23"
2. 使用toLocaleDateString/toLocaleString
这两个方法可以快速生成本地化的日期/日期时间字符串,也支持自定义配置:
// 生成「YYYY-MM-DD」格式 const date = new Date('2018-04-28T18:38:23Z'); const formattedDate = date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-'); console.log(formattedDate); // 输出 "2018-04-28" // 生成带时间的完整格式 const formattedDateTime = date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(/\//g, '-'); console.log(formattedDateTime); // 输出 "2018-04-28 18:38:23"
3. 手动拼接(适合简单固定格式)
如果只需要特定格式,直接提取日期各部分拼接也很简单:
const date = new Date('2018-04-28T18:38:23Z'); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需+1补位 const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; console.log(formatted); // 输出 "2018-04-28 18:38:23"
二、移除日期字符串中的GMT部分
针对你遇到的场景,想要去掉GMT-0500这部分,用字符串分割或截取就能轻松实现:
方法1:用split分割字符串
const date = new Date('2018-04-28T18:38:23Z'); const dateStr = date.toString(); const formattedDate = dateStr.split(' GMT')[0]; // 以「 GMT」为分隔符,取第一部分 console.log(formattedDate); // 输出 "Sat Apr 28 2018 18:38:23"
方法2:用slice截取到GMT之前
const date = new Date('2018-04-28T18:38:23Z'); const dateStr = date.toString(); const gmtIndex = dateStr.indexOf(' GMT'); const formattedDate = dateStr.slice(0, gmtIndex); console.log(formattedDate); // 输出 "Sat Apr 28 2018 18:38:23"
小提醒
你写的Date(2018-04-28T18:38:23Z)是错误的写法哦——直接调用Date()函数会返回当前日期字符串,正确创建日期对象的方式是new Date('2018-04-28T18:38:23Z'),之后调用toString()才会得到带GMT的字符串。
内容的提问来源于stack exchange,提问作者Dawn17
相关产品推荐
相关产品推荐

