feat: Performance dateLabel done.

This commit is contained in:
chiayin
2024-02-02 15:00:45 +08:00
parent d89c5ff4d8
commit 7c959e7cd9
2 changed files with 84 additions and 17 deletions

View File

@@ -1,3 +1,5 @@
import moment from 'moment';
/**
* 將秒數轉換成帶有時間單位的格式
* @param {number} Second
@@ -86,3 +88,41 @@ export function followTimeLabel(second, max, fixedNumber = 0) {
}
return result;
}
/**
* 將時間轉換成不同日期單位的格式
* @param { string } date 日期
* @param { string } maxX 該 data 最大的日期
* @param { string } minX 該 data 最小的日期
*/
export function dateLabel(date, maxDate, minDate) {
// 將時間字串轉換為時間物件
// new Date(time) 之後不用 getTime()因為在JavaScript中日期物件是以時間戳記timestamp的形式存儲的。當創建一個新的日期物件時它內部會自動轉換時間字串為時間戳記。
date = new Date(date);
maxDate = new Date(maxDate);
minDate = new Date(minDate);
// 計算時間差距
let timeDiff = maxDate - minDate;
// 計算相差的月份
var diffMonths = (maxDate.getFullYear() - minDate.getFullYear()) * 12;
diffMonths -= minDate.getMonth();
diffMonths += maxDate.getMonth();
console.log(diffMonths);
// 計算相差的日期,要取整數才能接續下方的邏輯判斷 `diffDays > 0`
// 毫秒 * 秒 * 分鐘 * 小時 = 一天的時間量
var diffDays = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
// 計算相差的小時、分鐘、秒
var diffHours = Math.floor(timeDiff / (1000 * 60 * 60));
var diffMinutes = Math.floor(timeDiff / (1000 * 60));
var diffSeconds = Math.floor(timeDiff / 1000);
// 顯示結果
if (diffMonths > 0) return moment(date).format('YYYY/MM/DD');
else if (diffDays > 0) return moment(date).format('MM/DD');
else if (diffHours > 0) return moment(date).format('MM/DD hh:00');
else if (diffMinutes > 0) return moment(date).format('MM/DD hh:mm');
else return moment(date).format('hh:mm:ss');
}