timeUtil.js

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 调用方法
// var date1 = new Date().Format("yyyy-MM-dd");
// var date2 = new Date().Format("yyyy-MM-dd HH:mm:ss");
const forMat = function (fmt,date) {
     let ret;
        const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 时
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以继续添加,必须转化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            };
        };
        return fmt;
}

module.exports = {
  formatTime: formatTime,
  forMat:forMat
}

`

页面中引用

import {forMat,formatTime} from "@/utils/timeUtil.js"

//转化为时间
var time= forMat("YYYY-mm-dd HH:MM:SS",new Date(Number(时间戳)))  //此处时间戳是秒的话*1000转化为毫秒

//转化为日期
var date = formatTime(new Date(Number(时间戳))).split(" ")[0]    //此处时间戳是秒的话*1000转化为毫秒
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐