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

Tips for leveraging OOP to eliminate redundant code repetition

How can I avoid repeating code when displaying multiple quizzes on the same page? Currently, I have a JavaScript function that duplicates everything for each quiz, with only a few variables changing in the second function. The problem arises when I need t ...

How can I tally the frequency of characters in a given string using Javascript and output them as numerical values?

I am in the process of tallying the frequency of each individual character within a given string and representing them as numbers. For example, let's consider the string "HelloWorld". HELLOWORLD There is one H - so 1 should be displayed with H remov ...

The default value of components in Next.js

I'm working on establishing a global variable that all components are initially rendered with and setting the default value, but I'm unsure about how to accomplish the second part. Currently, this is what I have in my _app.tsx: import { AppProps ...

Troubleshooting issues with environment variables in Next.js version 12.2.2

I tried following the steps outlined in the official documentation, but I'm encountering an issue. Here is what I did: next.config.js const nextConfig = { reactStrictMode: true, swcMinify: true, env : { MORALIS_ID: 'moralisId', ...

Exploring VueJS templating: Loading external templates

Being new to Vue.js, I have some experience with AngularJS where we used to load templates like this: template: '/sometemplate.html', controller: 'someCtrl' My question is how can we achieve something similar in Vue? Instead of embeddi ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. The essential functio ...

There are three pop-up windows displayed on the screen. When each one is clicked, they open as intended, but the information inside does not

Every button triggers a unique modal window Encountering an unusual problem with Bootstrap 5 modal functionality. Within a webpage displaying a list of database entries (refer to the screenshot), each entry features three buttons to open corresponding mod ...

What could be the reason why my sorting function is not functioning properly?

I am currently in a state of questioning everything I thought I knew. > [ 37, 4, 3, 1, 3, 10, 8, 29, 9, 13, 19, 12, 11, 14, 20, 22, 22, 27, 28, 33, 34 ].sort((a, b) => a > b) [19, 34, 3, 1, 3, 10, 8, 29, 9, 13, 4, 12, 11, 14, 20, 22, 22, 27, 28, ...

Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements. For example, consider this original array ...

Error in Angular 2: The app.component.html file triggered an exception at line 1, character 108 due to excessive recursion

After successfully setting up the Angular 2 quickstart and connecting to an express server, I encountered a problem when switching from using the template property to component templateUrl. I have created a Plunker to showcase this issue: Plunker Demo imp ...

Stopping JavaScript when scrolling to the top and running it only when not at the top

I found a great jQuery plugin for rotating quotes: http://tympanus.net/codrops/2013/03/29/quotes-rotator/ Check out this JSFiddle example: http://jsfiddle.net/LmuR7/ Here are my custom settings (with additional options that I haven't figured out yet) ...

Innovative form creation using Vue.js

My interactive form allows users to input an item, quantity, and cost per item like this: <form @submit.prevent="submit"> <div class="form-group" v-for="(input,k) in inputs" :key="k"> <input ty ...

What could be the reason for the three.js scene failing to render in my Svelte application?

Scene.svelte <!-- Start by binding a container, then add the renderer to this container onMount --> <script> import { onMount } from 'svelte'; import * as THREE from 'three'; let container; onMount(async () = ...

Exploring a JSON file to generate a customized array for implementing autocomplete functionality in jQuery

I'm currently working on developing an autocomplete feature for a search bar that will display names of places in Norway. The data is being fetched from a REST API URL provided by a third party. As an example, when the input is "st" there are two res ...

Issues persist with debugger functionality in browser development tools following an upgrade from Angular 8 to version 15

After upgrading from Angular version 8 to version 15, I've encountered an issue where the debugger is not functioning in any browser's developer tools. Can anyone provide some insight on what could be causing this problem? Is it related to the so ...

Tips for automatically refreshing a Next.js application following an update in an external library

I have a monorepo containing two applications: The first is a Next.js web app The second is a UI library using Tailwind CSS and Microbundle Currently, the only way I can get the web app to recognize changes made in the UI library is by following these st ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

How can I align rectangles with different heights to display side by side using Javascript?

Currently, I am designing a press page for a website where the headlines/articles are displayed in rectangles. To achieve this layout, I am using the following CSS: .press-blocks{ column-count: 4; column-gap: 2em; padding-left: 10%; padding ...

Conceal component while navigating in VueJs

I am working on a Vue project. I am trying to implement a feature where a component is hidden while the user scrolls, but then reappears once the scrolling stops. I have tried using a scroll event, but the component does not show up again. <div c ...

What is the significance of using index 0 for caching an ID in jquery?

What is the reason behind using an index of 0 in the following code? var $one = $('#one')[0]; Is there a specific purpose for not just using var $one = $('#one'); ? SOURCE I came across the above code while researching about jQuery, ...