时间格式转换
const transFormation = {
// 获取当前日期
getLocalTime() {
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const mins = date.getMinutes();
const seconds = date.getSeconds();
const time = `${year}-${transFormation.addZero(month)}-${transFormation.addZero(day)} ${transFormation.addZero(hour)}:${transFormation.addZero(mins)}:${transFormation.addZero(seconds)}`;
return time;
},
// 获取一周前日期
getWeekAgo() {
const now = new Date();
const date = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const mins = date.getMinutes();
const seconds = date.getSeconds();
const time = `${year}-${transFormation.addZero(month)}-${transFormation.addZero(day)} ${transFormation.addZero(hour)}:${transFormation.addZero(mins)}:${transFormation.addZero(seconds)}`;
return time;
},
// 获取当前时间前一天
getPrevDate() {
const now = new Date();
const date = new Date(now - 1000 * 60 * 60 * 24);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const mins = date.getMinutes();
const seconds = date.getSeconds();
const prevTime = `${year}-${transFormation.addZero(month)}-${transFormation.addZero(day)} ${transFormation.addZero(hour)}:${transFormation.addZero(mins)}:${transFormation.addZero(seconds)}`;
return prevTime;
},
// 当前时间的前两个小时
getPrevHour() {
const now = new Date();
const date = new Date(now - 2 * 60 * 60 * 1000);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const mins = date.getMinutes();
const seconds = date.getSeconds();
const prevHour = `${year}-${transFormation.addZero(month)}-${transFormation.addZero(day)} ${transFormation.addZero(hour)}:${transFormation.addZero(mins)}:${transFormation.addZero(seconds)}`;
return prevHour;
},
// 如果日期时间是单数前面添加0
addZero(s) {
return s < 10 ? `0${s}` : s;
},
// 标准时间转换成日期时间格式
timestampToTime(timestamp) {
const d = new Date(timestamp);
const resDate = `${d.getFullYear()}-${transFormation.addZero((d.getMonth() + 1))}-${transFormation.addZero(d.getDate())}`;
const resTime = `${transFormation.addZero(d.getHours())}:${transFormation.addZero(d.getMinutes())}:${transFormation.addZero(d.getSeconds())}`;
const formDate = `${resDate} ${resTime}`;
return formDate;
},
// 将图片url转成base64编码格式
// getBase64Image(img) {
// const canvas = document.createElement('canvas'); // 创建一个canvas
// canvas.width = img.width; // 设置对应的宽高
// canvas.height = img.height;
// const ctx = canvas.getContext('2d'); // 二维绘图环境
// ctx.drawImage(img, 0, 0, img.width, img.height); // 将图片画在画布上
// const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase(); // 获取到图片的格式
// const dataURL = canvas.toDataURL(`image/${ext}`); // 得到base64 编码的 dataURL
// return dataURL;
// },
};
export default transFormation;
网友评论