为避免我们在项目中多次进行时间转换 我们对时间转换进行封装,代码如下
创建date.js文件
在项目utils文件夹中创建date.js文件
一、时间戳格式化
export const getTime = (data,formate = "YYYY-MM-DD HH:mm:ss") => {
let value = Number(data.toString().split(".")[0]);
let dt = new Date(value * 1000);
let year = dt.getFullYear();
let month = (dt.getMonth() + 1 + "").padStart(2, "0");
let day = (dt.getDate() + "").padStart(2, "0");
let hour = (dt.getHours() + "").padStart(2, "0");
let min = (dt.getMinutes() + "").padStart(2, "0");
let second = (dt.getSeconds() + "").padStart(2, "0");
if (formate == 'YYYY') {
return year;
} else if (formate == 'YYYY-MM') {
return `${year}-${month}`;
} else if (formate == 'YYYY-MM-DD') {
return `${year}-${month}-${day}`;
} else if (formate == 'YYYY-MM-DD HH') {
return `${year}-${month}-${day} ${hour}:00`;
} else if (formate == 'YYYY-MM-DD HH:mm') {
return `${year}-${month}-${day} ${hour}:${min}`;
} else if (formate == 'YYYY-MM-DD HH:mm:ss') {
return `${year}-${month}-${day} ${hour}:${min}:${second}`;
}
}
使用方法
import { getTime} from '@/utils/date'
getTime(1692840599,'YYYY-MM-DD') //不传默认YYYY-MM-DD HH:mm:ss格式
二、日期格式化
export const parseDate = (time, formate = "YYYY-MM-DD HH:mm:ss") => {
if (!time) {
return "";
}
let date = new Date(time),
year = date.getFullYear(),
month = returnZero(date.getMonth() + 1),
day = returnZero(date.getDate()),
hour = returnZero(date.getHours()),
min = returnZero(date.getMinutes()),
second = returnZero(date.getSeconds());
if (formate == 'YYYY') {
return year;
} else if (formate == 'YYYY-MM') {
return `${year}-${month}`;
} else if (formate == 'YYYY-MM-DD') {
return `${year}-${month}-${day}`;
} else if (formate == 'YYYY-MM-DD HH') {
return `${year}-${month}-${day} ${hour}:00`;
} else if (formate == 'YYYY-MM-DD HH:mm') {
return `${year}-${month}-${day} ${hour}:${min}`;
} else if (formate == 'YYYY-MM-DD HH:mm:ss') {
return `${year}-${month}-${day} ${hour}:${min}:${second}`;
}
}
export const returnZero = (date) => {
//时间返回加0
return date < 10 ? "0" + date : date;
}
使用方法
import { parseDate } from '@/utils/date'
parseDate(new Date(),'YYYY-MM-DD') //不传默认YYYY-MM-DD HH:mm:ss格式