繁体   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