1.将当前日期转换为时间戳
var now = new Date();
console.log(now.getTime()) //1612886627039;当前的时间戳
console.log(now.valueOf()) //同上,都精通到秒
// 将当前日期转换为时间戳,getTime()方法可返回距1970年1月1日之间的毫秒数。
2.将时间戳转换为日期
getTime(time) { //年月日时分秒
var now = new Date(time)
var nian = now.getFullYear()
var yue = (now.getMonth() + 1).toString().padStart(2, '0')
var ri = now.getDate().toString().padStart(2, '0')
var shi = now.getHours().toString().padStart(2, '0')
var fen = now.getMinutes().toString().padStart(2, '0')
var miao = now.getSeconds().toString().padStart(2, '0')
return `${nian}-${yue}-${ri} ${shi}:${fen}:${miao}`
},
3.使用Moment.js
通过npm安装:npm install moment -S
import Moment from 'moment'
// 时间戳(毫秒)转化为标准时间格式
export function getTime(time)
{
const stamp = new Date(time)
const times = Moment(stamp).format('YYYY-MM-DD HH:mm:ss')
return times
}