时间戳转成时间格式化字符串(常用)
//formatData.js
//封装的formatDate函数
export 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);
};
//vue组件
<template>
  <div class="comment-info-wrap">
        <!--  commentInfo.created是传进来的时间戳65132165464,单位为秒 -->
        <span class="comment-time">
        <!-- 使用showDate方法对时间戳进行过滤格式化-->
        {{ commentInfo.created | showDate }}
        </span>
  </div>
</template>
<script>
import { formatDate } from "common/formatDate";
export default {
  name: "DetailCommentInfo",
  props: {
    commentInfo: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  filters: {
    showDate(value) {
      //将时间戳转换成date对象
      const date = new Date(value * 1000);//这里需要将时间戳乘以1000,转为毫秒,具体看请求过来的数据
      //将date进行格式化
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  }
};
</script>
步骤总结:
1.将时间戳转为Data对象,const date =new Date(1535694719*1000)
2.将date进行格式化,使用封装的formatDate函数即可
3.注意字母大小写:"yyyy-MM-dd hh:mm:ss"
4.hh为12小时,HH为24小时
    注:以上内容仅用于日常学习

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号