1.时间戳转换成2020-06-27 14:20:27
<template>
<div>
<van-field v-model='code' label='车牌号'></van-field>
<van-button @click='into'>进入</van-button>
<table>
<tr>
<td>车牌号</td>
<td>进入时间</td>
<td>操作</td>
</tr>
<tr v-for='i in list'>
<td>{{i.code}}</td>
<td>{{i.stime | changetime}}</td> #使用
<td>
<van-button @click='out(i.code)'>离开</van-button>
</td>
</tr>
</table>
</div>
</template>
<script>
#时间转换方法
function unixTimeToDateTime(unixtime){
var now = new Date(unixtime * 1000); // 依情况进行更改 * 1
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();
return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}
export default {
data(){
return{
code:'',
list:[]
}
},
methods: {
into(){
alert(this.code)
//获取到车牌号
//向接口发起请求
this.axios.post('into',{'code':this.code}).then(res=>{
if(res.data.code == 200){
alert('添加成功')
this.getlist()
}
})
},
getlist(){
//获取已经进入未离开的车辆
this.axios.get('into').then(res=>{
this.list = res.data.list
})
},
// 离开方法
out(code){
this.axios.post('out',{"code":code}).then(res=>{
if(res.data.code==200){
alert('本次交费'+res.data.money)
}
})
}
},
// 过滤器,过滤转换时间
filters:{
changetime(v){
return unixTimeToDateTime(v)
}
},
mounted() {
this.getlist()
},
}
</script>
<style>
</style>
2.将时间戳格式化
function formatDate(date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
}
}
return fmt
}
function padLeftZero(str) {
return ('00' + str).substr(str.length)
}
使用方法:
formatDate(date, 'yyyy-MM-dd hh:mm');
formatDate(date, 'yyyy-MM-dd');
3、将2020-06-27T14:20:27.000000Z 时间格式转换成 2020-06-27 14:20:27
可以将方法定义为全局过滤器,或全局方法方便引用
Vue.filter('format', function(date) {
var json_date = new Date(date).toJSON();
return new Date(new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
})
{{timeVal | format}}
4、Vue中使用moment.js(时间格式化插件);
安装moment.js插件
npm install moment --save
import moment from 'moment';
Vue.filter('dateFormat',function(value,format)){
return moment(value).format(format);
}
使用方法:
{{time | dateFormat('YYYY-MM-DD HH:mm:ss')}}
直接在Vue中定义成时间格式方法:
import moment from 'moment';
Vue.prototype.$moment = moment;
在vue文件中当作方法使用
this.$moment(timeVal).format('YYYY-MM-DD'); // 2022-02-11