簡體   English   中英

比較 Day.js 中的日期?

[英]Compare dates in Day.js?

如何檢查“2023 年 1 月 31 日星期二 00:00:00 GMT+0100”是否與“2023-01-31T18:45:00-06:00”同一天和同一月
這非常令人困惑。

let dates = [
{slot: '2023-01-31T18:45:00-06:00'}
{slot: '2023-01-31T19:00:00-06:00'}
{slot: '2023-01-31T19:15:00-06:00'}
{slot: '2023-01-31T19:30:00-06:00'}
{slot: '2023-01-31T19:45:00-06:00'}
{slot: '2023-01-31T20:00:00-06:00'}
]

let dayjsDate = dayjs('Tue Jan 31 2023 00:00:00 GMT+0100') // DateJS object!

dates.forEach(x => {
let oneSlot = dayjs(x.slot)
   if (oneSlot.isSame(dayjsDate, 'day')
        && oneSlot.isSame(dayjsDate, 'month')) {
        console.log("Yes")
   } else {
        console.log("No")
   }
})

我實際上並不熟悉 Day.js 或 momentjs(你的 2 個標簽),但我相信你可以在好的舊香草 JS 中做到這一點(意味着不需要包)。

我會先說我不是 JS 中的日期方面的專家,所以我的方法可能很奇怪。

我喜歡“規范化”沒有時區的日期,所以我從你稱為dayjsDate的源代碼開始

let source_date = "Tue Jan 31 2023 00:00:00 GMT+0100".split(' ');

source_date.pop();

source_date = new Date(source_date); //log would give "Tue Jan 31 2023 00:00:00 GMT-0500 (Eastern Standard Time)" since I'm in EST

(或者如果你想在一行中完成: let source_date = new Date("Tue Jan 31 2023 00:00:00 GMT+0100".split(' ').slice(0,-1));

然后,使用數組中的值,因為我們只關心日期部分,所以我會這樣做:

let dates = [ //directly from your post, but I added commas
  {slot: '2023-01-31T18:45:00-06:00'},
  {slot: '2023-01-31T19:00:00-06:00'},
  {slot: '2023-01-31T19:15:00-06:00'},
  {slot: '2023-01-31T19:30:00-06:00'},
  {slot: '2023-01-31T19:45:00-06:00'},
  {slot: '2023-01-31T20:00:00-06:00'},
];

let cleaned_dates = dates.map(x => new Date(x.slot.substring(0, 10) + 'T00:00:00')); //an array of dates

我們現在可以通過以下方式輕松比較日期:

cleaned_dates.forEach(x => isSame(x, source_date));

function isSame(date_1, date_2) {
    let same = (date_1.getMonth() === date_2.getMonth()) && (date_1.getDate() === date_2.getDate());
    if (same) console.log('Same');
    else console.log('Different');
    return same;
}

如果您還想按年份進行比較,您可以輕松添加另一個,例如&& date_1.getFullYear() === date_2.getFullYear() 這些是與Date對象一起使用的本機 JS 函數。

JS 中的函數是“提升”的,因此它們先於其他所有內容加載,因此可以在聲明之前調用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM