一、毫秒转成日期
1、后台返回毫秒,前端以yyyy-MM-dd hh:mm展示
2、全局定义一个过滤函数
// 时间格式化:毫秒转成日期(millisecond为毫秒值)
fromData: (millisecond) => {
let time = new Date(millisecond)
let month = time.getMonth() + 1 // 国际与国内区别
let date = time.getDate()
let hours = time.getHours()
let minutes = time.getMinutes()
// let second = time.getSeconds() // 获取秒数
// 小于10前加一个0
if(month < 10) {
month = '0' + month
}
if(date < 10) {
date = '0' + date
}
if(hours < 10) {
hours = '0' + hours
}
if(minutes < 10) {
minutes = '0' + minutes
}
// 拼接正确格式返回
return time.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + minutes
}
3、组件中的使用
<a-col :lg="8" :sm="24" class="desTxt">
创建时间:{{record.createTime | fromData}}
</a-col>
4、最后的效果
二、日期转成毫秒数
1、有时前端获取到的是日期,需要转毫秒给后台
2、定义一个函数
// 日期转成毫秒(date为日期),一般以毫秒传给后台
queryDate: (date) => {
// 通过.getTime() 方法直接返回毫秒数
return (new Date(date)).getTime()
}
3、组件中的使用
<a-col :lg="8" :sm="24" class="desTxt">
更新时间:{{ 1617179424000 | queryDate}}
</a-col>
4、最后的效果
5、拓展:
timeStampToDate (str) { // 时间戳转时间
let now = str ? new Date(str) : new Date(),
y = now.getFullYear(),
m = now.getMonth() + 1,
d = now.getDate();
return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
},
调用:
this.timeStampToDate(时间戳)
总结:
var oldTime = (new Date("2011/11/11 20:10:10")).getTime(); //得到毫秒数
var newTime = new Date(oldTime); //就得到普通的时间了
更详细的时间转化可以看这里:https://www.jb51.net/article/176589.htm
虽然辛苦,我还是选择滚烫的人生!