skip to Main Content

I am working with a JSON data that would look like this

[
    {
        "hourly_AQI": 73.0,
        "hourly_date": "Tue, 31 Oct 2023 11:00:00 GMT"
    },
    {
        "hourly_AQI": 79.0,
        "hourly_date": "Tue, 31 Oct 2023 13:00:00 GMT"
    },
    {
        "hourly_AQI": 77.0,
        "hourly_date": "Tue, 31 Oct 2023 14:00:00 GMT"
    }
]

And I also got a code which will make an array that the hourly_date is greater than local current time. But when I use and run the code at 18:03 the code would give me the time from 13:00:00 onward as a result why is that?

const now = new Date();
const filteredData = aqiData?.filter((item) => {  
    const date = new Date(item.hourly_date);
    // Check if the item's date is in the future
    return date >= now
});
console.log(filteredData)

I tried it at around 1 PM as well and it would give me a data from 7:00 am onward even I specify the code to give me greater or equal to. I’m confused please help!

2

Answers


  1. const now = new Date();
    const localTimeZone = 'your-time-zone-here';
    
    const formatter = new Intl.DateTimeFormat('en-US', { timeZone: localTimeZone, hour12: false });
    const filteredData = aqiData?.filter((item) => {  
        const date = new Date(item.hourly_date);
        const formattedDate = formatter.format(date);
    
        return new Date(formattedDate) >= now;
    });
    console.log(filteredData);
    Login or Signup to reply.
  2. you can convert the now Date object to GMT before doing the comparison.
    Here’s how you can do that:

    const now = new Date();
    const nowInGMT = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
    
    const filteredData = aqiData?.filter((item) => {  
        const date = new Date(item.hourly_date);
        // Check if the item's date is in the future
        return date >= nowInGMT;
    });
    console.log(filteredData);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search