简体   繁体   中英

Compare dates in Day.js?

How do I check if 'Tue Jan 31 2023 00:00:00 GMT+0100' is the same day and month as '2023-01-31T18:45:00-06:00' ?
It's very confusing.

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")
   }
})

I'm not actually familiar with Day.js or momentjs (your 2 tags) but I believe you can do this in good old vanilla JS (meaning no packages necessary).

I'll preface this by saying I'm no expert in Dates in JS, so my approach might be a weird one.

I like to "normalize" dates without timezones, so I start with your source one that you called dayjsDate as

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

(or if you want to do it in a single line: let source_date = new Date("Tue Jan 31 2023 00:00:00 GMT+0100".split(' ').slice(0,-1)); )

Then, with the values in your array, since we only care about the date portions, I would do:

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

We can now easily compare the dates, by virtue of something like:

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;
}

If you would also like to compare by year, you can easily add another like as && date_1.getFullYear() === date_2.getFullYear() . These are native JS functions that work with Date objects.

Functions in JS are "hoisted" so they load before everything else, so they can be called before they are declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM