最近在做公司项目时,遇到时间与时间戳的相互转换,这篇文章记录下。
效果如下:
需求是:
添加套餐的一个页面,上边有套餐的起始时间 和 截止时间 ,用的是element 日期选择组件,选择完之后,会把起始时间和截止时间 转化为时间戳发给后端,html代码如下:
<!-- value-format="timestamp" 把当前时间转化为时间戳 -->
<!-- 此组件数据是一个数组 -->
<el-date-picker
v-model="row.beginTime_endTime"
type="daterange"
is-range
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
format="yyyy 年 MM 月 dd 日"
value-format="timestamp"
/>
时间戳转化为时间
页面需要展示开始时间和结束时间,此时,需要把时间戳转化为正常年月日的格式:
// 时间戳转为正常时间的公共方法,当然你也可以加上小时、分、秒
filterTime(time) {
const date = new Date(time)
const Y = date.getFullYear()
const M = date.getMonth() + 1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1
const D = date.getDate()
return `${Y}-${M}-${D}`
},
// 在点击确认添加之后,调用filterTime方法,赋值给当前数据即可,下边是小时、分、秒
const H = date.getHours() // 小时
const M = date.getMinutes() // 分钟
const S = date.getSeconds() // 秒
// 下边这个方法是判断时间是否小于10,小于10 前边加0,更加规范一些,看自己需求
function isAddZero(time) {
let str = ''
if(time < 10) {
str = '0' + time
}else{
str = time.toString()
}
return str
// 方法二
let str = ''
str = time < 10 ? '0' + time : time.toString()
return str
}
时间转化为时间戳
当编辑的时候,需要把时间转化为时间戳,赋值给日期选择组件
function timeToTime(time) {
return new Date(time).getTime()
}
let res = timeToTime('2019-12-12')
console.log(res) // 1576108800000