JSON.stringify() 处理 Date

732 阅读1分钟

前言

我们一般在项目中处理 Date 一般会用 moment 插件,或者是使用 Date相关的方法。

获取 YY-MM-DD

方法一

const time = new Date()
const currentTime = `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDay()}`

用上面这种方法还要去补 0 的操作

方法二:使用 JSON.stringify

JSON.stringify(new Date()).replace(/T.*|"/g, "")
// 2019-07-02

获取 yyyy-mm-dd HH:mm:ss:fff

JSON.stringify(new Date()).replace(/T|"|\..*/g," ").trim()
//2019-07-02 02:39:17

如果你有更好的方式,欢迎留言,一起学习。