76 lines
2.1 KiB
JavaScript
76 lines
2.1 KiB
JavaScript
/**
|
||
* 将时间字符串格式化为时间对象
|
||
* @param {string} timeStr - 时间字符串,格式:2025/09/03 04:05:40
|
||
* @returns {Date} 时间对象
|
||
*/
|
||
function parseTimeString(timeStr) {
|
||
// 支持多种分隔符
|
||
const normalizedStr = timeStr.replace(/[\/\-]/g, '/');
|
||
return new Date(normalizedStr);
|
||
}
|
||
|
||
/**
|
||
* 将时间对象格式化为指定格式的字符串
|
||
* @param {Date} date - 时间对象
|
||
* @param {string} format - 格式字符串,如:yyyy-mm-dd HH:MM:ss
|
||
* @returns {string} 格式化后的时间字符串
|
||
*/
|
||
function formatTime(date, format) {
|
||
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');
|
||
|
||
return format
|
||
.replace('yyyy', year)
|
||
.replace('mm', month)
|
||
.replace('dd', day)
|
||
.replace('HH', hours)
|
||
.replace('MM', minutes)
|
||
.replace('ss', seconds);
|
||
}
|
||
|
||
/**
|
||
* 计算两个时间对象的时间差(不返回秒)
|
||
* @param {Date} time1 - 开始时间
|
||
* @param {Date} time2 - 结束时间
|
||
* @returns {string} 时间差描述,如:4小时 或 4小时10分钟
|
||
*/
|
||
function calculateTimeRange(time1, time2) {
|
||
// 确保time2晚于time1,否则交换
|
||
let startTime = time1;
|
||
let endTime = time2;
|
||
|
||
if (time1 > time2) {
|
||
startTime = time2;
|
||
endTime = time1;
|
||
}
|
||
|
||
const diffMs = endTime - startTime;
|
||
const diffMinutes = Math.floor(diffMs / (1000 * 60));
|
||
const diffHours = Math.floor(diffMinutes / 60);
|
||
const remainingMinutes = diffMinutes % 60;
|
||
|
||
let result = '';
|
||
|
||
if (diffHours > 0) {
|
||
result += `${diffHours}小时`;
|
||
}
|
||
|
||
if (remainingMinutes > 0) {
|
||
if (result) result += ' ';
|
||
result += `${remainingMinutes}分钟`;
|
||
}
|
||
|
||
// 如果时间差为0,返回0分钟
|
||
if (!result) {
|
||
return '0分钟';
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
export { parseTimeString, formatTime, calculateTimeRange }
|