我在项目中后端传回的时间为UTC格式的时间,我觉得转换为正常时间在页面中看起来更加直观,但是将数据传回后端时也需要转回UTC时间,不然就保存失败 ,跟后端沟通不来就只能自力更生啦,于是通过day.js互转时间格式
1、下载day.js
npm下载
npm install dayjs --save
2、引入day.js与utc插件
import dayjs from 'dayjs'import utc from 'dayjs/plugin/utc'dayjs.extend(utc)
3、封装转换方法
我封装在自己创建的js文件中导出
export function conversionUtcDate(date, type) {if (type === 'local') { // 传入local则将UTC时间转换为本地时间return dayjs.utc(date).local().format('YYYY-MM-DD HH:mm:ss')} else if (type === 'UTC') { // 传入UTC则将时间转换为UTC时间return dayjs(date).utc().format()}}
4、使用
导入方法(根据自己文件所在路径导入)
import { conversionUtcDate } from '@/utils/tools.js'
从后端获取数据时将UTC转换为本地时间
保存数据时将本地时间转换为UTC时间传回后端