Troubleshooting the issue: JavaScript's Time comparison failure with JSON versus Local time

Dealing with JSON data like the following:

[
    {
        "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"
    }
]

I have written code that creates an array of data where the hourly_date is greater than the current local time. However, when I run the code at 18:03, it only gives me data from 13:00:00 onwards. 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 also tried running the code around 1 PM, but it still returns data from 7:00 AM onwards, even though I specified greater than or equal to. I'm confused, please help!

Answer №1

const currentDateTime = new Date();
const localTimeZone = 'your-local-time-zone-here';

const formatter = new Intl.DateTimeFormat('en-US', { timeZone: localTimeZone, hour12: false });
const filteredData = aqiData?.filter((item) => {  
    const dataDate = new Date(item.hourly_date);
    const formattedDate = formatter.format(dataDate);

    return new Date(formattedDate) >= currentDateTime;
});
console.log(filteredData);

Answer №2

To ensure accurate comparison, convert the current Date object to GMT before proceeding. Follow these steps to achieve this:

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);
    // Confirm if the item's date lies in the future
    return date >= nowInGMT;
});
console.log(filteredData);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the best ways to engage with a div element using keyboard shortcuts?

Is it possible to enable keyboard shortcuts for interacting with div elements? I am working on a project tailored for seniors who may have difficulty using a mouse. Is there a way to utilize keyboard shortcuts to click on divs and access their contents? H ...

Differences between React class properties and ES6 class properties

With React 16.2, defining class properties is done differently with the tagLine example shown below: class Header extends React.Component { tagLine = "Super Hero"; render() { .... } } Contrastingly, in ES6 classes, it's not possible to define ...

Disregarding TypeScript import errors within a monorepo ecosystem

In my Turborepo monorepo, I have a Next.js app package that imports various components from a shared package. This shared package is not compiled; it simply contains components imported directly by apps in the monorepo. The issue arises with the shared co ...

Issues with NGRepeat causing AJAX JSON errors

Facing an issue with displaying JSON data fetched from the server (Node.js) in NGrepeat. Various attempts have been made to troubleshoot using Firebug and Firefox Web Inspector. Despite the JSON data appearing correct when viewed in the Firebug console ( ...

Issue with Vue components causing dropdowns and modals to malfunction until a page refresh

While working with Vue.js and Laravel 5.4, I have encountered an issue where everything functions correctly in the .blade.php files, but not in the .Vue files. Specifically, nothing occurs when I click on a dropdown or a modal button. Strangely, everythi ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...

What is the most efficient way to integrate JSON Data into a Line of Business Web Application?

Typically, I've been using JSON with jQuery to return HTML strings. However, I'm interested in transitioning to JavaScript objects in my code. What's the easiest way for me to begin using JSON objects on my webpage? Below is a sample Ajax ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

Guide to dynamically loading a component using a variable name in Vue.js?

Is it possible to dynamically load a component in a vue.js application using a variable name? For example, if I have the following component registered: <template id="goal"> <h1>Goal:{{data.text}}</h1> </template> Instead of di ...

Here are the steps to trigger a pop-up window in JavaScript that is filled with data fetched via an AJAX call:

I'm currently working on a java class where I need to insert a link into a table grid. This code is specific to the internal API of our company. /***MyCustomLink.java*********/ customLink.setOnClick( "fetchURL", return false;); addGridItem("cu ...

Exploring a JavaScript object to verify if a property contains nested data elements

I am currently working on traversing through the object above in order to determine if a contact is a member of a specific list. For instance, if the user is a member of the list with an ID of 2022, I want to display their first name (which is also includ ...

Is there a problem with the string comparison in my JavaScript code?

I am dealing with various XML files specific to different operating systems. Here is an excerpt from the SunOS XML: <osname>SunOS </osname> This data is extracted using jQuery: var osname = $(this).find('osname').text(); However ...

The React.useCallback hook in Cube.js is missing a dependency, specifically 'pivotConfig'. This could potentially cause unexpected behavior in the application

After multiple attempts at creating a straightforward dashboard using Cube.js with Windows 10 and MySQL version 8, I am feeling frustrated. Initially, I experimented with a JavaScript backend, struggled through the installation process for days, then attem ...

Ways to acquire ttf files from a third-party domain without encountering CORS issues

I am attempting to obtain a .ttf file from an external website for use in my web application. However, when I try the following code: @font-face { font-family: 'font'; src: url('http://xxx.xyz/resources/tipografias/font.ttf') forma ...

Tips for transferring a variable from Next.js to a plain JavaScript file

When it comes to Canvas Dom operations in my NextJs file, I decided to include a Vanilla JS file using 'next/script'. The code for this is: <Script id="canvasJS" src="/lib/canvas.js" ></Script>. Everything seems to ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

Encountering the error message: "Error -[__NSArrayM city]: unrecognized selector sent to instance 0x111c03460"

Can someone assist me with using Google's geocoding API to retrieve the city name and geolocation? I am encountering an error in my code and need help identifying where the issue lies. Below is the snippet of my code: ViewController: - (void)search ...

Retrieve data from a jQuery AJAX request and perform further jQuery actions upon its successful completion

I am trying to figure out how to use jQuery AJAX to duplicate a background image and then return information back to the original page. When the '#dupBtn' is clicked, the following AJAX is sent... //DUPLICATE BACKGROUND $('#dupBtn&apo ...

The error occurred while trying to cast the value of "{{Campground.name}}" to an ObjectID. This value, which is of type string, could not be converted to an ObjectID at the path "_id" for

const express = require("express"); const session = require("express-session"); const cookieParser = require('cookie-parser') const mongoose = require("mongoose"); const { Campground, User, Review } = require(" ...

I am attempting to send an array as parameters in an httpservice request, but the parameters are being evaluated as an empty array

Trying to upload multiple images involves converting the image into a base64 encoded string and storing its metadata with an array. The reference to the image path is stored in the database, so the functionality is written in the backend for insertion. Ho ...