vue使用js时间格式化

本文介绍了如何在Vue应用中使用JavaScript将中国标准时间转换为常见日期格式,如2020-6-20 10:00:00。同时,讲解了如何将时间戳转换为日期,并提供了一个后台传递时间戳到前端时的封装调用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js格式转换

1.中国标准时间转换为正常格式:
在这里插入图片描述

	 let date = this.start_timestamp; 
     let date_value = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();

转换后格式为:2020-6-20 10:00:00
将时间转换为时间戳 :

let millisecond = Date.parse(date_value);

2.封装调用(当后台传递过来时间戳形式如:1592589641 这样的形式)

// 时间戳转换
export function formatDateTime(date, fmt) {
  if (!date) {
   return ''
  }
  date *= (date.toString().length === 10 ? 1000 : 1)
  let _date = new Date(date)
  let _fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
  let o = {
   'M+': _date.getMonth() + 1,
   'd+': _date.getDate(),
   'h+': _date.getHours(),
   'm+': _date.getMinutes(),
   's+': _date.getSeconds()
  }
  if (/(y+)/.test(_fmt)) {
   _fmt = _fmt.replace(RegExp.$1, (_date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
   if (new RegExp('(' + k + ')').test(_fmt)) {
    _fmt = _fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
   }
  }
  return _fmt
 }

调用HTML中

 <el-table-column label="活动购买时间(区间)" align="center">
          <template slot-scope="scope">{{scope.row.start_time | formatTime}} - {{scope.row.end_time  | formatTime}}</template>
        </el-table-column>
        <el-table-column label="活动核销时间(区间)" align="center">
          <template slot-scope="scope">{{scope.row.use_start_time  | formatTime }} - {{scope.row.use_end_time  | formatTime }}</template>

js部分

 filters:{
    formatTime(time) {
      console.log(time);
        if (time == null || time === '') {
          return 'N/A';
        }
        return formatDateTime(time, 'yyyy-MM-dd hh:mm:ss')
      },
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值