这是我参与更文挑战的第8天,活动详情查看: 更文挑战
1. 前言
打工仔正认真搬砖、突然收到条朋友的信息、问我如下问题: 如何将UTC时间转成YYYY-MM-DD HH:MM:SS格式的时间?
当时看到第一眼、这啥玩意儿、没见过这种格式的啊? 故有了此文章的输出, 用于介绍如何将UTC格式时间进行格式化。
2. 实现方案
'2021-06-23T07:00:00.5872'为UTC时间格式;
new Date()创建的是Date对象, 可用于获取时间戳、格式化时间等。
function formatDate (v){
if(v){
// 将Date()对象转成YYYY-MM-DD HH:MM:SS格式
const year = v.getFullYear()
const month = v.getMonth() + 1 < 10 ? `0${v.getMonth() + 1 }`: v.getMonth()
const day = v.getDate() + 1 < 10 ? `0${v.getDate() + 1 }`: v.getDate()
const hour = v.getHours() < 10 ? `0${v.getHours()}`: v.getHours()
const minute = v.getMinutes() < 10 ? `0${v.getMinutes()}`: v.getMinutes()
const second = v.getSeconds() < 10 ? `0${v.getSeconds()}`: v.getSeconds()
return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}
return ''
}
const createTime = '2021-06-23T07:00:00.5872'
// 这里是关键、将UTC格式转成Date对象!!!!!! -> 指定日期
const tmp = new Date(createTime)
// 区别于new Date() -> 返回一日期对象: 当前时间
console.log(formatDate(tmp))
至此已经解决了你的问题、后面的可不看。But建议来都来了、学习下更好哟~
3. new Date() IOS兼容
我们经常会用YYYY-MM-DD HH:MM:SS格式来表示日期、也经常会把此格式的字符串转化为Date对象、如下
const Time = '2021-06-28 15:26:45'
该代码chrome、360等web浏览器、安卓设备上均正常;But在safari浏览器上却报错、报错信息为: Invalid Date(无效时间).
解决方案:
// 将“-”替换成“/”就OK了、安卓/ios都兼容了.
const Time = '2021-06-28 15:26:45'
Time = new Date(Time.replace(/-/g, "/"));
4.写在最后
若有错误之处, 恳请留言, 定会及时更正!
若觉着对您有帮助的话恳请点个赞或着收藏吧!