如下:
/**
* @description 获取某种格式的当前时间/指定时间字符串
* @param format 期望的日期格式
*/
export const getFormatTime = (format: string = '', timestamp?, withPrefixZero = false) => {
const time = timestamp ? new Date(timestamp) : new Date();
const year = time.getFullYear();
const month = withPrefixZero ? formatTimeNum(time.getMonth() + 1) : time.getMonth() + 1;
const date = withPrefixZero ? formatTimeNum(time.getDate()) : time.getDate();
const hours = withPrefixZero ? formatTimeNum(time.getHours()) : time.getHours();
const minutes = withPrefixZero ? formatTimeNum(time.getMinutes()) : time.getMinutes();
const seconds = withPrefixZero ? formatTimeNum(time.getSeconds()) : time.getSeconds();
const millisecond = this.formatTimeNum(time.getMilliseconds(), 3);
switch (format) {
case 'yyyy-mm-dd':
return [year, month, date].join('-');
case 'yyyymmddHHMMSS':
return [year, month, date, hours, minutes, seconds].join('');
case 'yyyy-mm-dd HH:mm:ss':
return `${[year, month, date].join('-')} ${[hours, minutes, seconds].join(':')}`;
default:
return [year, month, date].join('-');
}
};
// 时间前面补上0
formatTimeNum = (time: number, digit = 2) => {
let str = time.toString();
while (str.length < digit) {
str = '0' + str;
}
return str;
};
/**
* @description 时间戳转换成00:00:00格式
* @param timestamp 时间戳(兼容数字和字符串格式)
*/
export const formatTime = (timestamp: number | string) => {
let time: number;
let showTime: string;
if (timestamp) {
const val = typeof timestamp === 'string' ? parseInt(timestamp, 10) : timestamp;
const ss = 1000;
const mi = 60;
const hh = mi * 60;
// 取整数秒
time = parseInt(String(val / ss), 10);
if (time !== null) {
const hour = parseInt(String(time / hh), 10);
const minute = parseInt(String((time % hh) / mi), 10);
const second = parseInt(String((time % hh) % mi), 10);
showTime = `${formatTimeNum(hour)}:${formatTimeNum(minute)}:${formatTimeNum(second)}`;
} else {
showTime = '00:00:00';
}
} else {
showTime = '00:00:00';
}
return showTime;
};
/**
* 查询当天日期 yyyymmddHHMMSS
*/
export const getNowDate = () => {
const timeOne = new Date();
const year = timeOne.getFullYear();
let month = timeOne.getMonth() + 1;
let day = timeOne.getDate();
let hour = timeOne.getHours();
let min = timeOne.getMinutes();
let second = timeOne.getSeconds();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hour = hour < 10 ? '0' + hour : hour;
min = min < 10 ? '0' + min : min;
second = second < 10 ? '0' + second : second;
const NOW_MONTHS_AGO = `-${year}${month}${day}${hour}${min}${second}`;
return NOW_MONTHS_AGO;
};
/**
* @description 时间转换为东八区时间
* @param timestamp 时间
*/
export const toBeiJingTime = (dateStr: number | string) => {
const timezone = 8;
const offset = new Date().getTimezoneOffset();
const value = Math.min(new Date(dateStr).valueOf(), new Date().valueOf());
const date = new Date(value + offset * 60 * 1000 + timezone * 60 * 60 * 1000);
return getFormatTime('yyyy-mm-dd HH:mm:ss', date, true);
};
/**
* 获取当前时区 GMT+xx:xx 或 GMT-xx:xx
*/
export const getGMT = () => {
const timeOffset = new Date().getTimezoneOffset();
const timeZone = -timeOffset / 60;
const hour = Math.floor(Math.abs(timeZone));
const minute = (Math.abs(timeZone) - hour) * 60;
const timeZoneHourNum = formatTimeNum(hour);
const timeZoneMinuteNum = formatTimeNum(minute);
const symbolOfGMT = timeZone >= 0 ? '+' : '-';
return `GMT${symbolOfGMT}${timeZoneHourNum}:${timeZoneMinuteNum}`;
};
// 计算两个日期的差
export const getRelativeTime = (time) => {
if (!time) return '--';
const startTime = time;
const endTime = new Date().getTime();
const diff = (endTime - startTime) / 1000;
if (isNaN(diff)) {
// 如果startTime是脏数据导致计算出nan,直接返回
return '--';
}
const day = parseInt(String(diff / (24 * 60 * 60)), 10); // 计算天
const afterDay = diff - day * 24 * 60 * 60; // 取得扣除天数后剩余时间
const hour = parseInt(String(afterDay / (60 * 60)), 10); // 计算小时
const afterHour = diff - day * 24 * 60 * 60 - hour * 60 * 60; // 取得扣除天数 小时后剩余时间
const min = parseInt(String(afterHour / 60), 10); // 计算分
const afterMin = diff - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60; // 取得扣除天数 小时 分钟后剩余时间
const second = parseInt(String(afterMin), 10); // 计算秒
const year = parseInt(String(day / 365), 10); // 计算年
const month = parseInt(String(day / 30), 10); // 计算月
const week = parseInt(String(day / 7), 10); // 计算星期
if (year) {
return `${year}年前`;
} else if (month) {
return `${month}月前`;
} else if (week) {
return `${week}周前`;
} else if (day) {
return `${day}天前`;
} else if (hour) {
return `${hour}小时前`;
} else if (min) {
return `${min}分钟前`;
} else if (second) {
return `${second}秒前`;
} else {
return '--';
}
};