Experiencing NaN output while trying to calculate the date difference in Javascript

I'm currently working on this code snippet to calculate the difference between two dates, but unfortunately, I keep getting NaN as the output. Can anyone spot where I might be going wrong?

    var start = "01/01/2018"; //dd/mm/yyyy format
    var end = "09/01/2018"
    var date1 = new Date(start);
    var date2 = new Date(end);

    var timeDiff = Math.abs(date1.getTime() - date2.getTime());
    var diffDays = Math.ceil(parseInt((date2 - date1) / (24 * 3600 * 1000)));

    alert(diffDays);

Answer β„–1

It's puzzling why you were encountering NaN as the result - it seems likely that you may have been using slightly different code than what is displayed here. One thing to consider is that the browser interprets 09/01/2018 as the 1st of September, rather than the 9th of January as you might anticipate. Due to this behavior and your use of Math.abs, you're actually seeing a value of 242 instead of the expected 8.

To avoid ambiguity when specifying dates, it's recommended to utilize the format yyyy-mm-dd, which will be interpreted accurately in all scenarios.

The provided code below functions correctly (yielding the anticipated output) across Chrome, Firefox, and Internet Explorer/Edge:

var start = "2018-01-01"; // yyyy-mm-dd format
var end = "2018-01-09";
var date1 = new Date(start);
var date2 = new Date(end);

var timeDiff = Math.abs(date1.getTime() - date2.getTime());
var diffDays = Math.ceil(parseInt((date2 - date1) / (24 * 3600 * 1000)));

console.log(diffDays);

Answer β„–2

The solution provided below successfully solves the issue. Hopefully, it will prove beneficial to others as well. Thank you to everyone who contributed!

var start = "01/01/2018";


var startD = new Date(start);
var end = "09/01/2018";
var endD = new Date(end);


var report_date_string = new String(start);
var rectify_date_string = new String(end);

var report_date_final = report_date_string.split('/');
var month1 = report_date_final[0];
var day1 = report_date_final[1];
var year1 = report_date_final[2];

var rectify_date_final = rectify_date_string.split('/');
var month2 = rectify_date_final[0];
var day2 = rectify_date_final[1];
var year2 = rectify_date_final[2];

var report_datetime = new Date(year1,  day1,month1 - 1);


var rectify_datetime = new Date(year2, day2,month2 - 1);


var diff = Math.abs(((rectify_datetime.getTime() - report_datetime.getTime()) / (24 * 3600 * 1000)));

alert(diff);

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

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

What is the best way to transfer an id from JavaScript to Rails while utilizing ajax?

Is there a way to call a rail route and pass in an ID from javascript? I have recently started using rails routes within my application, even in js. The current code I am using is: # app/assets/javascript/verifying_link.js $.ajax({ url: "/verify_link/ ...

Guide on properly accessing a properties file in JavaScript within the project directory?

I am currently working on developing a Chrome Packaged App. My goal is to store the script configuration in a config file within a designated resource directory, and then use Javascript to read this configuration upon startup. For instance: Project We ...

Is there a more efficient method for implementing React OnChange for each field?

When calling an API, receiving a payload and loading it into state in React, we often encounter situations where we have multiple fields to update. This can lead to creating numerous onChange functions for each field. Is there a more efficient pattern tha ...

Replace an NPM package with a completely different package

As per the official NPM documentation, utilizing the overrides feature in the package.json file allows for the substitution of a package with an entirely different one: Overrides serve as a means to swap out a package within your dependency hierarchy wit ...

Webpack encounters difficulty resolving non-js `require`s located within node_modules

In my Next.js project, I have set up the configuration to handle imports ending in .web.js, which works fine except for files within the node_modules directory. For this setup, I adjusted the webpack config by setting resolve.extensions = ['.web.js&ap ...

Modifying pagination numbers with Reactjs: A step-by-step guide

I am currently working on Reactjs (nextjs) and I have successfully integrated the "Nextjs" framework. The pagination is working fine, but the buttons are displaying as "1,2,3,20" instead of "1,2...20" (showing all numbers without using "..."). How can I mo ...

Ways to switch text on and off smoothly using transitions

I have created a webpage where text starts off hidden but has a visible heading. When you click on the heading, the text is revealed below. I am putting the final touches and aiming to make the text slide in smoothly. I am using Javascript for toggling ins ...

Automated playback of integrated Twitter video

Is there a way to make embedded Twitter videos autoplay? The code generates an iframe which is preventing me from using some JavaScript click tricks. Is there a workaround to enable autoplay? Plunker <script>window.twttr = (function(d, s, id) { v ...

β€œCan you confirm if this syntax is correct for defining methods in Vue.js?”

When defining methods in my Vue app, I have chosen to use the following format: methods: { myMethod(arg) { // do something here } } Although it is more common to see it written like this: methods: { myMethod: function (arg) { // do somethi ...

Trouble with custom font causing text to be cut off in h1 and h2 sizes when window is

Update: After using a custom font "Gotham" in the @font-face, I encountered several bugs that seem to stem from this source. I'm unsure of how to resolve these issues while still retaining my custom font. Any suggestions? Update #2: The problem was r ...

JavaScript Variable Naming ConventionEnsuring correct spelling in variable names is essential

While I may not be a JavaScript expert, I have a question about its dynamically typed nature. We are all aware that JavaScript (node.js) is a dynamically typed language where we can easily assign values like: someObject.attr = 123; However, due to the la ...

Customize a div's background color with an Angular directive

Imagine having a div element: <div id="wrapper"> some text </div> How can you create an angular directive that changes the background based on user input? For instance, you might have tried: <div id="wrapper" color temperature="51"> ...

What is the best way to access the "materials" array from my JSON file when using THREE.JS?

Previously, this code was functioning correctly on an outdated THREE.JS version: var loader = new THREE.JSONLoader(); loader.load("ns.js", function(geometry){ mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial(geometry.materials) ...

Insert a scrollbar into the new popup window on Internet Explorer after the window has been opened

I am looking to enable scrolling in a pop-up window after it has been opened. While FireFox offers the 'window.scrollbars' property for this, Internet Explorer does not have a similar feature. Is there a way to add scrolling functionality in IE u ...

JavaScript - Organizing Objects

I have successfully implemented a code to group objects by their category. Here is the code snippet: let groupBy = (element, key) => { return element.reduce((value, x) => { (value[x[key]] = value[x[key]] || []).push(x); return ...

Delete class at waypoints

I am currently using waypoints.js to manage a single-page website that includes a highlighted navigation feature. When the viewport reaches the element with the class "content", the corresponding navigation point is given the class "active". The script i ...

What is the best way to transform an array of strings into a JSON object?

When navigating back to a list page, I want to make sure that the filter criteria are still retained. My solution involves using cookies, which are set when the form filter is submitted. In the list page's mounted hook, I retrieve the specific cookie ...

Load the React component asynchronously while waiting for the data to be fetched

My ReactJS component looks like this: import React, {useState} from 'react'; import Plot from 'react-plotly.js'; import {utility} from "./utility"; function Chart() { const [use_data, setData] = useState([]); c ...

Transferring Variables from WordPress PHP to JavaScript

I have implemented two WordPress plugins - Snippets for PHP code insertion and Scripts n Styles for JavaScript. My objective is to automatically populate a form with the email address of a logged-in user. Here is the PHP snippet used in Snippets: <?p ...