From 29675af82b490c8d1a31d9f6f7690021ca107b31 Mon Sep 17 00:00:00 2001 From: Cindy Chang Date: Fri, 7 Jun 2024 08:54:21 +0800 Subject: [PATCH] add setTimeStringFormatBaseOnTimeDifference --- src/module/timeLabel.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/module/timeLabel.js b/src/module/timeLabel.js index c92574a..daa7f73 100644 --- a/src/module/timeLabel.js +++ b/src/module/timeLabel.js @@ -185,3 +185,33 @@ export function dateLabel(date, maxDate, minDate) { else if (diffMinutes > 0) return moment(date).format('MM/DD hh:mm'); else return moment(date).format('hh:mm:ss'); } + +/** + * Select an appropriate time format based on the time difference. + * 根據時間差距選擇適合的時間格式 + * 月: 2022/06 + * 日: 06/06 + * 時: 03/05 12:00 + * 分: 03/05 12:15 + * 秒: 09:05:32 + * @param {Array} timestamps - An array of timestamps. + * @returns {string} - The suitable time format string. + */ +export const setTimeStringFormatBaseOnTimeDifference = (minTimeStamp, maxTimeStamp) => { + const timeDifferenceInSeconds = (maxTimestamp - minTimestamp) / 1000; + + let dateFormat; + if (timeDifferenceInSeconds < 60) { + dateFormat = 'HH:mm:ss'; // 秒 + } else if (timeDifferenceInSeconds < 3600) { + dateFormat = 'MM/DD HH:mm'; // 分鐘 + } else if (timeDifferenceInSeconds < 86400) { // 86400 秒 = 24 小時 + dateFormat = 'MM/DD HH:mm'; // 小時 + } else if (timeDifferenceInSeconds < 2592000) { // 2592000 秒 = 30 天 + dateFormat = 'MM/DD'; // 天 + } else { + dateFormat = 'YYYY/MM'; // 月 + } + + return dateFormat; +};