incorrect calculation of date difference using momentjs

Currently utilizing countdown.js for a project where I need to add 60 days to a date fetched from the database. Successfully implemented this in the targetDay variable and it's functioning properly. However, when attempting to calculate this date from the current date, an unexpected result of

"1969-11-05T21:24:07.416Z"
is being returned - why?

const nowDate = moment();
const targetDay = moment('2020-10-24 14:25:26').add('60', 'days');
const countdown = moment(nowDate - targetDay);


console.log(countdown);
//const diff = targetDay.fromNow();

const count_days = countdown.format('D');
const count_hours = countdown.format('HH');
const count_minutes = countdown.format('mm');
const count_seconds = countdown.format('ss');
console.log(count_days + ' days:' + count_hours + ' hrs:' + count_minutes + ' m:' + count_seconds + ' s');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Experimented with the fromNow() function, but it only returns as a string. My objective is to create a countdown to the target day starting from the present time.

Answer №1

To determine the remaining time, you can use the .duration() method along with .hours(), .minutes(), and .seconds() to extract the respective values from the milliseconds.

Check out this link for more information on durations in Moment.js

const nowDate = moment();
const targetDay = moment('2030-10-24 14:25:26').add('60', 'days'); // I changed to 2030 to keep this snippet live for future ;)
const countdown = moment.duration(targetDay.diff(nowDate));
const count_days = Math.floor(countdown.asDays());
const count_hours = countdown.hours();
const count_minutes = countdown.minutes();
const count_seconds = countdown.seconds();
$('div').text(count_days + ' days:' + count_hours + ' hrs:' + count_minutes + ' m:' + count_seconds + ' s');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<div></div>

For demonstration purposes, it is advised to remove the setInterval function from your code.


I updated the year to 2030 for the longevity of this example ;)

Answer №2

Opt for using moment.diff() over manual mathematical subtraction.

This method will result in a moment.duration (usually in milliseconds).

const nowDate = moment();
const targetDay = moment('2020-10-24 14:25:26').add('60', 'days');
const countdownDiff = targetDay.diff(nowDate)
// 4855463420

Make sure to keep your constants as durations since the added difference is not directly a duration itself.

For example, adding 60 days to 28 October results in 28 December. However, moment('28-12-2020').format('D') will be 28, not the desired 60.

To handle this, separate and store them individually as differences.

const count_days = targetDay.diff(nowDate, 'd');
const count_hours = targetDay.diff(nowDate, 'h');
const count_minutes = targetDay.diff(nowDate, 'm');
const count_seconds = targetDay.diff(nowDate, 's');

If you need to convert it back to a moment object, simply add the difference to the original one as shown below.

const countdown = nowDate.add(countdownDiff, 'ms')
// While redundant, this clearly illustrates the calculation of diff

Below is a functional example:

const nowDate = moment();
const targetDay = moment('2020-10-24 14:25:26').add('60', 'days');
const countdownDiff = targetDay.diff(nowDate)
// 4855463420


const countdown = moment(nowDate).add(countdownDiff, 'ms')
// This line mirrors targetDay

const count_days = targetDay.diff(nowDate, 'days');
const count_hours = targetDay.diff(nowDate, 'h');
const count_minutes = targetDay.diff(nowDate, 'm');
const count_seconds = targetDay.diff(nowDate, 's');

console.log('Current day:', nowDate.format('Do MMM YYYY HH:mm'));
console.log('Target day:', targetDay.format('Do MMM YYYY HH:mm'));
console.log('Countdown end date', countdown.format('Do MMM YYYY HH:mm'));

console.log(count_days + ' days:' + count_hours + ' hrs:' + count_minutes + ' m:' + count_seconds + ' s');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

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

Sending a JavaScript variable to a Flask url_for function

There is an endpoint that requires a value in the URL and then generates content to be displayed within a specific div. I'm trying to construct the URL using url_for with a JavaScript variable, but it seems that $variable1 is being treated as a string ...

How to create a fresh factory instance in Angular Js

I have implemented a factory in my application to retrieve a list of folders and display it on the front end. Additionally, I have a form on the front end where users can add new folders to the existing list. After adding a folder, I need to refresh my fac ...

What is the best way to implement Angular 2 slash routes in conjunction with Node Express?

I have defined some routes in my App component: @routeConfig([ { path:'login', name: 'Login', component: Login }} Additionally, I have a basic node express loader set up: var express = require('express'); var ...

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...

A guide to dynamically extracting values from JSON objects using JavaScript

I have a JSON array with a key that changes dynamically (room number varies each time I run the code). My goal is to access the inner JSON array using this dynamic key. Here's what I've attempted so far, but it's throwing an error. Here is ...

Refresh web content dynamically without having to reload the entire page using JavaScript

Currently, I am struggling to find a solution on how to dynamically update a section of a webpage using JavaScript when a user modifies an input field in another part of the same page. Unfortunately, my use of document.write is inhibiting me from making th ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

Steps to implement jQuery after executing the command "npm install jquery"

Greetings! I recently utilized npm install jquery to add jQuery to my project. However, I noticed that it was downloaded into node_modules\jquery along with some unnecessary files. My goal is to only move node_modules\jquery\dist\jquer ...

Techniques for removing a label value using JavaScript

There is a label named "test" being generated from the .cs [C# code] with the text "data saved successfully". However, when I click the save button, I want to clear its text. Currently, I have 3 required field validators with messages [cannot be blank, can ...

Unable to set $_POST value when using $.ajax post request

I am a beginner in the world of PHP and JavaScript, and I have encountered an issue where I need to make changes to values in an XML document that has been read in. Specifically, I have an HTML Select element that was dynamically generated by PHP code. fu ...

Lock the initial column in an HTML table

Hey there! I've been trying to freeze the first column of my HTML table, and while I managed to do so after a few attempts, I encountered an issue. When I scroll the table horizontally, the columns on the left seem to overlap with the first column, an ...

Is it possible for me to generate c3js graphs dynamically?

Here is my current progress: <div id="chart"></div> <script> var names = <?php echo json_encode($array1) ?>; var count = <?php echo json_encode($array2) ?>; var x=0; while (names[x]!=null) ...

The loading cursor in IE7 flickers incessantly, causing the webpage to lag and become un

When I move my cursor and click in text fields, the page becomes unresponsive and shows a wait cursor. If you're curious to see this issue in action, check out this video. This problem is specific to IE7. I've attempted to identify any ajax re ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

The countdown timer resets upon the conditions being rendered

I have been using the 'react-timer-hook' package to create stopwatches for each order added to an array. The problem I encountered was that every stopwatch, across all components, would reset to zero and I couldn't figure out why. After a lo ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Showcasing two sets of data from an array using chart.js within a node.js environment

I am currently working on a project where I need to display two elements from an array - one as the label (e.g. "name of certain type of crop") and the other as the data itself (e.g. "quantity of the crop"). However, I am facing an issue where if the same ...

"Sharing fields between mongoose models: How can I reference a field from one model in another

I am currently working on linking specific fields from the User model to the Card schema using the username as a reference point. Let me provide an example using my Card schema: const CardSchema = new mongoose.Schema({ text: { type: String, ...