0
点赞
收藏
分享

微信扫一扫

js获取时间戳转化成日期格式的直接使用和封装


 一、在页面中直接使用

1.  通过模板字符串使用:

{{ times }}


2.  定义变量存放时间:

data() {
  return {
    times: "",
  };
},

3.  在 mounted() 方法里调用:

mounted() {
  const date = new Date();
  const Y = date.getFullYear();
  const M = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
  const D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  const h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  const m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  this.times = Y + "-" + M + "-" + D + " " + h + ":" + m;
},

二、封装函数(推荐)

1.  在单独的 js 文件内书写格式化的代码:

// 封装转化时间格式的函数,js时间戳转化成日期格式
export function timestampToTime(timestamp) {
   const time = new Date(timestamp);
   const Y = time.getFullYear();
   const M = time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1;
   const D = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
   const h = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
   const m = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
   const s = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
   return Y + "-" + M + "-" + D + " " + h + ":" + m;
}

2.  导入方法并使用:

多个方法可以在main.js内全局导入
import "./utils/time";

js获取时间戳转化成日期格式的直接使用和封装_时间格式_04

在使用到该方法的页面按需导入(推荐)
import { timestampToTime } from "@/utils/time";

js获取时间戳转化成日期格式的直接使用和封装_时间格式_05

3.  定义变量存放时间并使用:

data() {
  return {
    times: "",
  };
},

4.  在 mounted() 函数中获取当前时间戳并转化为固定格式赋值给定义的变量显示:

(这里我已经在js文件中return时指定显示格式)

mounted() {
  let time = +new Date();
  this.times = timestampToTime(time);
  // this.times = timestampToTime(time, 'yyyy-mm-dd h:m:s');
},

三、其他

可以通过路由传参把获取的时间在另一个页面使用:路由传参


举报

相关推荐

0 条评论