日期格式化 YYYY-MM-DD 出现时间偏移量
在js中,很多时候需要把日期字符串转换为一个 Date 对象。
如果得到的日期字符串有时间还好办,如果没有时间,只有日期的格式,例如 2022-12-01
这样的字符串呢?
大部分人可能什么都没想,直接就调用了 new Date(datestring)
。可是事情没有想象中那么简单。
发现了问题了吗?获得日期时间被减去了 5 个小时。
这是因为我们的浏览器在美国东部时间。
在 MDN 中,有一个下面的注释:
Note: When parsing date strings with the Date constructor (and Date.parse, they are equivalent), always make sure that the input conforms to the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for RFC 2822 format strings is by convention only. A library can help if many different formats are to be accommodated.
Date-only strings (e.g. "1970-01-01") are treated as UTC, while date-time strings (e.g. "1970-01-01T12:00") are treated as local. You are therefore also advised to make sure the input format is consistent between the two types.
不要忽略掉上面的这个注释。
用人话解释一下就是,如果直接给 new Date 传入’YYYY-MM-DD’ 这样的字符串作为参数的话,得到的 Date 对象是一个基于 UTC 的对象实例。
如上面的代码实例中,
const date2 = new Date('2022-12-01')
date2 在进行实例化的时候,得到的是 2022-12-01 00:00:00 GMT+00:00 这样的时间,再被转换美国的东部时区的时候,就少了 5 个小时。
问题解决
要解决这个问题,其实就使用了 moment 来对日期进行格式化就可以了。
moment('2022-12-01').toDate();
使用上面的代码,就可以避免在 new Date() 进行日期格式化的时候因为时区的问题导致的时间便宜。
这个便宜有可能会导致多一天或者少一天的情况。
处理日期,还是尽量使用 moment 库吧。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2020-12-02 Docker 添加容器到一个网络
2020-12-02 Docker 创建你自己的桥接网络