Search code examples
reactjsdatefilterluxon

How to map/filter data correctly with luxon (DateTimeNow) and ReactJs


I would like to explain my problem of the day.

I have a array which looks like this

[{status: "closed",createdAt: "2022-01-13T15:28:25.239Z"},{status: "closed",createdAt: "2022-01-10T15:28:25.239Z"},{status: "open",createdAt: "2021-11-25T15:28:25.239Z"}]

I filter to retrieve only the data with the status "closed"

const countData = data?.filter(
    (item) => item.status === "closed"
);
const count = countData?.length;

this works well, it correctly returns the number to me.

I would like to add a new filter with Luxon.

I would like to take the date of today with luxon, and, as a result, display the objects that correspond to this date

const dateNow = DateTime.now().toISO();
console.log(dateNow) 
2022-01-13T16:23:44.873+01:00

How can I fix this issue?


Solution

  • If you want to check if a given Luxon DateTime object represent the same day of today, you can use hasSame passing date as second parameter

    Return whether this DateTime is in the same unit of time as another DateTime. Higher-order units must also be identical for this function to return true. Note that time zones are ignored in this comparison, which compares the local calendar time. Use DateTime#setZone to convert one of the dates if needed.

    In your case, you can have something like the following code:

    const DateTime = luxon.DateTime;
    const input = [{
      status: "closed",
      createdAt: "2022-01-13T15:28:25.239Z"
    }, {
      status: "closed",
      createdAt: "2022-01-10T15:28:25.239Z"
    }, {
      status: "open",
      createdAt: "2021-11-25T15:28:25.239Z"
    }, {
      status: "closed",
      createdAt: new Date().toISOString()
    }];
    
    const todayItems = input.filter(item => {
      return DateTime.fromISO(item.createdAt).hasSame(DateTime.now(), 'day') && item.status == "closed";
    });
    console.log(todayItems)
    <script src="https://cdn.jsdelivr.net/npm/luxon@2.3.0/build/global/luxon.js"></script>