React 獲取今日結束時間 23:59:59

  獲取今日結束時間 23:59:59 封裝起來作法

export function getTodayEndTime() {
const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1).getTime() / 1000;
return end;
}

若不轉換時間軸 可以移除後面 .getTime() / 1000

在想要引用的檔案引用

import { getTodayEndTime } from '封裝js路徑';
console.log('今日結束時間', getTodayEndTime())


代碼優化:

export function getTodayEndTime() { const start = Math.floor(Date.now() / (24 * 60 * 60 * 1000)) * (24 * 60 * 60 * 1000); const end = start + 24 * 60 * 60 * 1000 - 1; return Math.floor(end / 1000); }


優化說明:

  1. 使用 Math.floor() 方法將時間戳整數化,避免因為除法產生的小數位誤差導致計算結果出錯。

  2. 使用 Date.now() 方法簡化獲取當前時間的代碼,並將其單位轉換為秒。

  3. 利用乘法和除法,將當天的起始時間轉換為秒數,避免使用 new Date() 方法和字符串操作,提高代碼執行效率。

  4. 將獲取結束時間的代碼拆分為兩行,提高代碼的可讀性和維護性。

  5. 利用 Math.floor() 方法將結束時間的毫秒數轉換為秒數,保持函數的返回值和參數單位一致,方便後續處理。

留言

熱門文章