1、js 时间戳转日期(可直接复制)在js中将时间戳转换为常见的时间格式,有三种主要的方法
1、用JS中已有些函数,比如getFullYear(),getMonth()等,将时间戳直接转换成对应的年月;
2、创建时间过滤器,在其他的页面中直接调用该过滤器,转换时间戳;
3、用day.js,将时间戳转换成常见的时间写法
4、本文以vue2和vue3两个后台管理软件中的下单时间为例,将原来的时间戳转换为年月日的形式,其中vue2用js和element ui,vue3用TS和element-plus
//时间戳lettimestamp=1662537367//此处时间戳以毫秒为单位letdate=newDate(parseInt(timestamp)*1000);letYear=date.getFullYear();letMoth=(date.getMonth()+110?0+(date.getMonth()+1):date.getMonth()+1);letDay=(date.getDate()10?0+date.getDate():date.getDate());letHour=(date.getHours()10?0+date.getHours():date.getHours());letMinute=(date.getMinutes()10?0+date.getMinutes():date.getMinutes());letSechond=(date.getSeconds()10?0+date.getSeconds():date.getSeconds());letGMT=Year+-+Moth+-+Day++Hour+:+Minute+:+Sechond;console.log(GMT)//2022-09-0715:56:07
附加
letnowTime=newDate().valueOf();//时间戳console.log(nowTime)//获得目前时间的时间戳2、在main.js中创建过滤器
示例:后台管理软件,vue2 + JS + element ui,将下单时间的时间戳转换为年月日的形式
(1)main.js中,创建过滤器将它挂载到vue上
注意:我这边后台返回的数据需要进行单位换算,所以originVal * 1000,具体状况具体剖析,不同单位的数据请自行调整
importVuefromvue//创建过滤器,将秒数过滤为年月日,时分秒,传参值originVal为毫秒Vue.filter(dateFormat,function(originVal){//先把传参毫秒转化为newDate()constdt=newDate(originVal*1000)consty=dt.getFullYear()//月份是从0开始,需要+1//+是把数字转化为字符串,padStart(2,0)是把字符串设置为2位数,不足2位则在开头加0constm=(dt.getMonth()+1+).padStart(2,0)constd=(dt.getDate()+).padStart(2,0)return`${y}-${m}-${d}`})
(2)页面中具体用
el-table:data=orderListborderstripeclass=mt20el-table-columnlabel=下单时间prop=create_timetemplateslot-scope=scope{{scope.row.create_time|dateFormat}}/template/el-table-column/el-table3、day.js(链接直达)
(1)三种安装方法任选其一
npminstalldayjscnpminstalldayjs-Syarnadddayjs
(2)页面中具体用
示例:后台管理软件,vue3 + TS + element-plus,将下单时间的时间戳转换为年月日的形式
用前:

用后:

① html部分
npminstalldayjscnpminstalldayjs-Syarnadddayjs
②获得到的数据

③TS部分
对拿到的数据中的创建时间进行转换,其中dayjs()中携带需要转换的时间戳参数,format()中携带所期待转换成的形式
//引入import{dayjs}fromelement-plus;interfaceIOrderList{order_number:string;//订单编号create_time:number;//下单时间}constorderList=reactiveIOrderList[]([]);//获得订单数据constgetOrderList=async()={orderList.length=0;letorders=awaitordersAPI(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();





