91 lines
2.8 KiB
JavaScript
91 lines
2.8 KiB
JavaScript
|
|
export const formatDateTime = (date = new Date()) => {
|
|
// 确保传入的是 Date 对象
|
|
if (!(date instanceof Date)) {
|
|
date = new Date(date);
|
|
}
|
|
|
|
// 提取日期时间各部分
|
|
const year = date.getFullYear();
|
|
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
const day = String(date.getDate()).padStart(2, '0');
|
|
const hours = String(date.getHours()).padStart(2, '0');
|
|
const minutes = String(date.getMinutes()).padStart(2, '0');
|
|
const seconds = String(date.getSeconds()).padStart(2, '0');
|
|
const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
|
|
const timezoneOffset = -date.getTimezoneOffset();
|
|
const timezoneHours = String(Math.floor(Math.abs(timezoneOffset) / 60)).padStart(2, '0');
|
|
const timezoneMinutes = String(Math.abs(timezoneOffset) % 60).padStart(2, '0');
|
|
const timezoneSign = timezoneOffset >= 0 ? '+' : '-';
|
|
|
|
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
|
|
}
|
|
|
|
export const getTimeDifference = (time1, time2) => {
|
|
// 将时间字符串转换为 Date 对象
|
|
const date1 = new Date(time1);
|
|
const date2 = new Date(time2);
|
|
|
|
// 计算时间差(毫秒)
|
|
const diffMs = Math.abs(date2 - date1);
|
|
|
|
// 转换为分钟
|
|
const diffMinutes = Math.floor(diffMs / (1000 * 60));
|
|
|
|
// 计算小时和分钟
|
|
const hours = Math.floor(diffMinutes / 60);
|
|
const minutes = diffMinutes % 60;
|
|
|
|
// 确定时间差的方向
|
|
const direction = date2 > date1 ? "之后" : "之前";
|
|
|
|
return {
|
|
hours,
|
|
minutes,
|
|
totalMinutes: diffMinutes,
|
|
direction
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 比较两个时间字符串(格式:HH:MM)
|
|
* @param {string} time1 - 第一个时间字符串,如 "14:00"
|
|
* @param {string} time2 - 第二个时间字符串,如 "15:00"
|
|
* @returns {number}
|
|
* -1: time1 在 time2 之前
|
|
* 0: time1 等于 time2
|
|
* 1: time1 在 time2 之后
|
|
* @throws {Error} 如果时间格式无效
|
|
*/
|
|
export function compareTimes(time1, time2) {
|
|
// 验证时间格式
|
|
const timeRegex = /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/;
|
|
|
|
if (!timeRegex.test(time1) || !timeRegex.test(time2)) {
|
|
throw new Error('时间格式无效,请使用 HH:MM 格式(24小时制)');
|
|
}
|
|
|
|
// 将时间字符串转换为分钟数进行比较
|
|
const timeToMinutes = (time) => {
|
|
const [hours, minutes] = time.split(':').map(Number);
|
|
return hours * 60 + minutes;
|
|
};
|
|
|
|
const minutes1 = timeToMinutes(time1);
|
|
const minutes2 = timeToMinutes(time2);
|
|
|
|
if (minutes1 < minutes2) return 1;
|
|
if (minutes1 > minutes2) return -1;
|
|
return 0;
|
|
}
|
|
|
|
|
|
// 数字转16进制字符串
|
|
export const numberToHex = (number) => {
|
|
return (number & 0xFF).toString(16).padStart(2, '0')
|
|
}
|
|
|
|
// 延迟执行
|
|
export const delay = (ms) =>{
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
} |