JS时间戳转换方式示例详解(js如何将时间戳转换为时间)越早知道越好

随心笔谈12个月前发布 admin
102 0



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

在js中将时间戳转换为常用的时间格式,有三种主要的方式

1、使用JS中已有的函数

,例如,等,将时间戳直接转换成对应的年月;

2、创建时间过滤器

,在其他的页面中直接调用该过滤器,转换时间戳;

3、使用,将时间戳转换成常用的时间写法

4、本文以vue2和vue3两个后台管理系统中的下单时间为例,将原本的时间戳转换为年月日的形式,其中vue2使用js和element ui,vue3使用TS和element-plus

// 时间戳
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) // 获取当前时间的时间戳

示例:后台管理系统,,将下单时间的时间戳转换为年月日的形式

(1)中,创建过滤器将其挂载到vue上

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)页面中具体使用

<el-table :data=”orderList” border stripe class=”mt20″>
<el-table-column label=”下单时间” prop=”create_time”>
<template slot-scope=”scope”>
{{scope.row.create_time | dateFormat}}
</template>
</el-table-column>
</el-table>

(1)三种安装方式任选其一

npm install dayjs
cnpm install dayjs -S
yarn add dayjs

(2)页面中具体使用

示例

:后台管理系统,,将下单时间的时间戳转换为年月日的形式

使用前:

使用后:

① 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<IOrderList[]>([]);
// 获取订单数据
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时间戳转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:JS的时间格式化和时间戳转换函数示例详解Vue.js 时间转换代码及时间戳转时间字符串js实现把时间戳转换为yyyy-MM-dd hh:mm 格式(es6语法)js时间戳与日期格式之间转换详解js时间戳与日期格式之间相互转换JavaScript时间戳与时间日期间相互转换javascript时间戳和日期字符串相互转换代码(超简单)JS获取时间的相关函数及时间戳与时间日期之间的转换

© 版权声明

相关文章