elementui时间戳转-JS时间戳转换方法实例解读

2024-05-24 0 1,315 百度已收录

目录前言 1.将js时间戳转换日期(可直接复制) 2.在main.js创建过滤器 3.day.js(直接链接

前言 js 上将时间戳转换为常见时间格式主要有三种形式

1、利用JS中已有的函数,如getFullYear()、getMonth()等,直接将时间戳转换为对应年份和月份;

2、创建时间过滤器,在其他页面直接调用该过滤器,并转换时间戳;

3.使用day.js将时间戳转换为常用的时间写入方式

4、本文以vue2、vue3两个后端管理系统中的订单时间为例,将原始时间戳转换为年月日。 vue2使用js和element-uielementui时间戳转,vue3使用TS和element-plus。

1.将js时间戳转换为日期(可以直接复制)

    // 时间戳 
    let timestamp = 1662537367
    // 此处时间戳以毫秒单位
    let date = new Date(parseInt(timestamp) * 1000);
    let Year = date.getFullYear();
    let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
    let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
    let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    let  GMT =  Year + '-' + Moth + '-' + Day + '   '+ Hour +':'+ Minute  + ':' + Sechond;
    console.log(GMT)  // 2022-09-07 15:56:07

额外

let nowTime = new Date().valueOf();//时间戳
console.log(nowTime) // 获取当前时间的时间戳

2.在main.js中创建一个过滤器示例后台管理系统elementui时间戳转,vue2 + JS + element ui,如何将订单时间的时间戳转换为年月日。

(1)在main.js中,创建一个filter并挂载到vue上

注:我的后端返回数据需要进行单位转换,所以originVal * 1000。具体情况具体分析。 不同单位的数据请自行调整

import Vue from 'vue'
// 创建过滤器,将秒数过滤为年月日,时分秒,传参值originVal为毫秒
Vue.filter('dateFormat', function(originVal){
  // 先把传参毫秒转化为new Date()
  const dt = new Date(originVal * 1000)
  const y = dt.getFullYear()
  // 月份是从0开始,需要+1
  // +''是把数字转化为字符串,padStart(2,'0')是把字符串设置为2位数,不足2位则在开头加'0'
  const m = (dt.getMonth() + 1 + '').padStart(2, '0')
  const d = (dt.getDate() + '').padStart(2, '0')
  return `${y}-${m}-${d}`
})

(2) 页面中的具体使用

	
		
			{{scope.row.create_time | dateFormat}}
		
	

3.day.js(直接链接)(1)三种安装方式选任意三种

npm install dayjs
cnpm install dayjs -S
yarn add dayjs

(2) 页面中的具体使用

示例:后端管理系统,vue3 + TS + element-plus,如何将订单时间的时间戳转换为年月日

使用前:

使用后:

①html部分

npm install dayjs
cnpm install dayjs -S
yarn add dayjs

获得的数据

③TS部分

转换接收到的数据中的创建时间,其中dayjs()携带需要转换的时间戳参数format()携带需要转换的方法

// 引入
import { dayjs } from "element-plus";
interface IOrderList {
  order_number: string; // 订单编号
  create_time: number; // 下单时间
}
const orderList = reactive([]);
// 获取订单数据
const getOrderList = async () => {
  orderList.length = 0;
  let orders = await ordersAPI(pageInfo.value);
// 对 orders.data.goods进行遍历,dayjs()中携带需要转换的时间戳参数,format()中携带所期待转换成的形式
  orders.data.goods.forEach((el: any) => {
    el.create_time = dayjs(el.create_time * 1000).format("YYYY-MM-DD");
  });
  orderList.push(...orders.data.goods);
};
getOrderList();

这篇关于JS时间戳转换方法的文章到此结束。 更多相关js时间戳转换内容搜索之前的文章或者继续浏览下面的相关文章。 希望大家以后也能支持我!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悟空资源网 elementui elementui时间戳转-JS时间戳转换方法实例解读 https://www.wkzy.net/game/202271.html

常见问题

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务