js 時間 - daniel-qa/Vue GitHub Wiki
- 將 時間字串,轉換為 UNIX Time (se)
// 先取得發送時間,並轉換為 Unix 時間戳(毫秒)
const dateString = '2026/1/1 上午11:11:00';
const sendTime = dayjs(dateString, 'YYYY/M/D A h:mm:ss').valueOf(); // 轉換為毫秒
console.log(sendTime);
- 將 UNIX Time 轉換為 YYYY-MM-DD HH:mm
sendTime: dayjs(item.sendTime).format('YYYY/MM/DD HH:mm'),
hh → 是 12 小時制(需要搭配 A / a 使用)
HH → 是 24 小時制
dayjs 是一個輕量級的 JavaScript 日期時間處理庫,它在語法上與 Moment.js 非常相似,但體積更小。
- EX1:
import dayjs from 'dayjs'
const now = dayjs(); // 取得當前時間
const sendTime = dayjs(noticeForm.send); // 將發送時間轉為 dayjs 格式
if (sendTime.isBefore(now)) {
ElMessage.error('預約發送時間必須是未來的時間!');
return; // 停止執行,避免發送
}
- Ex2:
// 設定發送時間 (檢查是否是未來的時間)
if (noticeForm.send !== 0) { // 如果不是立即發送
const now = dayjs(); // 取得當前時間
const sendTime = dayjs(noticeForm.send); // 將發送時間轉為 dayjs 格式
if (sendTime.isBefore(now)) {
ElMessage.error('預約發送時間必須是未來的時間!');
return; // 停止執行,避免發送
}
else {
requestData.value.send = noticeForm.send; // 設定發送時間
}
}
之所以能夠使用 .isBefore() 這個方法來比較 sendTime 是否早於 now,正是因為 sendTime 和 now 都被轉換成了 dayjs 物件。
JavaScript 原生的 Date 物件雖然可以用比較運算符(<、>、<=、>=)進行比較,但它本身並沒有像 dayjs 那樣提供 .isBefore(), .isAfter(), .isSame() 等更語義化的時間比較方法。
dayjs 庫提供了豐富的 API 來方便進行日期和時間的操作與比較。
isBefore() 就是其中一個非常有用的方法,它使得時間的比較邏輯更加清晰易懂。
dayjs() 函式會創建一個 dayjs 物件,代表當前的日期和時間(會受到你之前設定的時區影響)。
dayjs(noticeForm.send) 函式會嘗試將 noticeForm.send 這個變數的值轉換成一個 dayjs 物件。這個值可以是一個符合 dayjs 可解析格式的日期時間字串、Unix 時間戳(毫秒或秒)、或者另一個 Date 物件等。
只有當你擁有了 dayjs 物件之後,才能調用它所提供的諸如 .isBefore()、.isAfter()、.isSame() 等方法。
因此,sendTime.isBefore(now) 能夠運作,關鍵在於 sendTime 和 now 都是 dayjs 的實例。