The d3.max function is returning inaccurate date values

I've encountered a strange issue while working on an overview page. I need to display the maximum date from loaded data to provide users with the time period they're looking at. Even though I already know what date it should be (either today or yesterday, updated nightly), I still want to use a max function as a failsafe in case of any update errors.

The problem arises when both d3.max and my custom max-date function return an incorrect date - one month ahead. For example, if today's date is supposed to be 7/9/2015, it displays as 7/10/2015 instead. This results in an empty array when trying to filter data for 7/10. Interestingly, this code works fine in a fiddle, so there might be some underlying issue. Could it have something to do with the d3.tsv (even though the file is actually tab-separated despite the .csv extension)? Any thoughts on where I could be going wrong? The parse function itself returns correct results, with dates formatted as dd.mm.yyyy.

//Dateformatting
function parseDate(dateStr) {
    var s1 = dateStr.split(" ");
    var s1dat = s1[0].split(".");
    return new Date(s1dat[2], s1dat[1], s1dat[0]);
};

var dateArr = [];

//Occupation
d3.tsv("data.csv", function(error, data, tsv) {
    datasetIn = data;
    datasetIn.forEach(function(d) {
        d.datum = parseDate(d.datum);
        d.Patients = +d.Patients.replace(",", ".");
        d.Beds= +d.Antal_vardplats.replace(",", ".");
    });
    
    for (index = 0; index < datasetIn.length; ++index) {
        dateArr.push(datasetIn[index].datum);
    }
    
    var maxYear = d3.max(dateArr).getFullYear();
    var maxDate = d3.max(dateArr);
})

Answer №1

When working with JavaScript, it's important to remember that month values start at 0 for January and go up to 11 for December. So if you try to create a Date object using the value of 9 for September, you might actually end up with a date in October instead.

new Date("2015", "9", "7").toDateString();  // "Wed Oct 07 2015"

To avoid this issue, make sure to adjust your input values accordingly when dealing with human-readable dates in JavaScript.

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 distinguishes the act of altering attributes using React.createContext() in comparison to the value property?

Imagine you have the code snippet below: //App.js //logoutHandler function defined here function App { const testContext = React.createContext({ isLoggedIn: false, onLogout: logoutHandler }) return ( <testContext.Provider> //Some code w ...

The Raycaster intersections in Threejs are not updated in real-time when objects are added to the scene, but

Currently, I am in the process of developing a Minecraft-inspired game using Three.js. At the moment, my setup involves adding cubes to a scene along with a Raycaster that identifies if the pointer is hovering over any of the cubes. It then creates an ind ...

Encountering difficulty locating the $wpdb variable during an AJAX request

I am currently developing a PHP application for WordPress and facing a challenge in retrieving a value from a database using AJAX every 2 seconds. I have created a new function in a separate file to handle this task. <?php global $wpdb; function retrie ...

Creating a Component and Programmatically Returning a Value in Vue.js: A Step-by-Step Guide

Could you assist me in solving my issue? I am looking to develop a customized plugin for my project so that my team and I can easily implement an alert component without having to design the dialog box repeatedly on every page and vuejs file. My objective ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

Ways to determine the visibility status of an HTML tag in Angular 2

Is there a way to check if a div is hidden in Angular 2? ...

Most effective method for storing and retrieving data on the client side

In my ASP web application, I am facing a challenge with listboxes as changes in item selection happen frequently and quickly. This results in slow performance when trying to retrieve the necessary information through postbacks. So, I am trying to figure o ...

Loading Ajax dropdown with a preselected value in the dropdown menu

There are two pages, each containing a form. Page 1 - Form A) Includes a dropdown menu (with values populated from the database) and a continue button. <select name="form[formA][]" id="dropdown1"> <option value="1">Option 01</opti ...

Navigating the integration of internal Bootsrap 5.2 with Laravel 7

Hi there, I am new to the Laravel framework and I am attempting to link my Bootstrap v5.2 with my Laravel v7 project. However, I seem to be having trouble connecting the two. I have stored the CSS and JS folders within a "bootstrap" folder at the same leve ...

Showing the URL beyond the search bar: A Guide using PHP, JavaScript, and HTML

How can I display the URL link outside the search box instead of opening a new page with the search result? I want to show the full URL (https://www.php.net.) below the search box, not within the search results. I only want to see the URL, not the contents ...

Create a stylish navigation dropdown with MaterializeCSS

Incorporating the materializecss dropdown menu feature, I encountered an issue where only two out of four dropdown menu items were visible. Here is the HTML code snippet in question: <nav class="white blue-text"> <div class="navbar-wrapper con ...

Leverage Reveal.js within Next.js by installing it as an npm package

I am currently working on a project that requires integrating Reveal.js with Next.js. However, I am having trouble displaying the slides properly. Every time I try to display them, nothing shows up. Even after attempting to display some slides, I still en ...

Issue with second button in Angular Onclick() not been resolved

I'm experiencing an issue with the onClick() methods in my code. There are two onClick() methods present on the UI, but when I click on the second one, it does not call the method while the first one does. I am struggling to figure out why this is hap ...

What are the advantages and disadvantages of utilizing ajax for form submission?

Lately, I've been relying heavily on AJAX for submitting forms like user registration and login. However, I'm curious about the safety of using AJAX for sensitive data like usernames and passwords. Can you provide some insight into the pros and c ...

What is the best way to create an express route for a delayed string response that is loaded only after an API call promise is fulfilled?

app.get(`/${sumName}`, async (req, res) => { const link = `https://na1.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5?api_key=${RiotKey}` const response = await fetch(link); let data = await response.j ...

Exploring the Intersection of jQuery and Rails in Dynamic Form Development

I am currently working on an interactive form for a Rails project and need some assistance with listing multiple jQuery functions in the same file. Whenever I try to add a second set of code language, it seems to break the entire file. Below is the Rails ...

Determining the JavaScript event source within a function's scope: A guide

Query Can we determine the origin of a function being triggered by either a user event or an async event, without having access to the original event parameter? Situation I am faced with the challenge of identifying the event source within a nested funct ...

I am unable to log the response, but I can view it in Postman and the network tab

Currently, I am working on setting up a register feature with a specific endpoint. The challenge I am facing revolves around handling validation responses from the backend. For instance, if I attempt to register with a username that is less than six charac ...

Innovative guidelines originating from a resource attribute

I am facing a challenge with a repeater for a resource that has an attribute containing angular directives mixed with text. My goal is to display form inputs dynamically based on the object's property. <ul> <li ng-repeat="action in actions ...

Converting Image to Base64 String and Parsing into a JSON Object

Hey there, I'm currently working on creating a form where users can input their information along with an image. My goal is to send all this data together in a JSON object back to the Node.js server. In order to include the image, I've been attem ...