The MomentJS difference calculation is incorporating an additional hour

I am currently working on a project that involves time calculations.

const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid');
const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid');
console.log('current',currentCETTime.format('HH:mm:ss'));
console.log('limit', limitCETTime.format('HH:mm:ss'));
const seconds = Math.abs(limitCETTime.diff(currentCETTime) / 1000);
console.log('hours', (seconds / 60) / 60);
const rem = moment(seconds * 1000);
console.log('diff', moment(rem).tz('Europe/Madrid').format('HH:mm'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>

Unfortunately, I have encountered an issue with the time difference calculation:

https://i.sstatic.net/nJNBW.png

The expected result is a difference of 2:01 hours instead of displaying as 03:01.

Answer â„–1

If you print out the entire date of rem, the issue becomes visible:

const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid');
const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid');
console.log('current',currentCETTime.format('HH:mm:ss'));
console.log('limit', limitCETTime.format('HH:mm:ss'));
const seconds = Math.abs(limitCETTime.diff(currentCETTime) / 1000);
console.log('hours', (seconds / 60) / 60);
const rem = moment(seconds * 1000);
console.log('diff', moment(rem).tz('Europe/Madrid').toString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>

When you call moment on a milliseconds value, it creates a new date from the epoch.

The difference in seconds is accurate. For the difference in hours, calling diff with the 'hours' argument would give you the result. It's important to note that moment rounds down to the nearest whole value.

const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid');
const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid');
console.log('current',currentCETTime.format('HH:mm:ss'));
console.log('limit', limitCETTime.format('HH:mm:ss'));
const hours = limitCETTime.diff(currentCETTime, 'hours');
console.log('hours', hours);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>

Answer â„–2

For just displaying the hour and second, there is no need to involve timezones. Simply call utc and then format the time. See the example code snippet below.

const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid');
const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid');
console.log('current',currentCETTime.format('HH:mm:ss'));
console.log('limit', limitCETTime.format('HH:mm:ss'));
const seconds = Math.abs(limitCETTime.diff(currentCETTime) / 1000);
console.log('hours', (seconds / 60) / 60);
const rem = moment(seconds * 1000);
console.log('diff', moment(rem).utc().format('HH:mm'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>

Answer â„–3

When using the moment(milliseconds) function
, both the regular and tz variants will add the milliseconds to the date 1970-01-01 01:00:00. According to the unix timestamp parser documentation, this is the expected behavior for this method. As a result, when the output is formatted, it may appear as if there is an extra hour included. This is because the calculation starts at hour 1 rather than hour 0. To verify this behavior, try passing in 0 for the total number of milliseconds and observe that the function still returns an hour value of 1.

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

Is there a way to update the input box value with a variable using jquery?

I am currently facing an issue with changing the value attribute of an input box in a form using jquery. Although I am able to change the value, it does not reflect in the outer html. Below is my current code snippet: $("a").click(function(event) { va ...

absence of data in ajax response (or HTTP status code 206 Partial Content)

Feeling frustrated because I've wasted two hours trying to solve a simple task that I've done numerous times before. I'm not even sure where to start looking now. Struggling to retrieve static content using ajax from local servers (Apache a ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

How can I create a static navigation bar and sidebar using Bootstrap 4?

Currently, I am utilizing HTML, Javascript, Bootstrap, and CSS to develop a fixed navbar and sidebar for our system. My objective is to ensure that the navbar and sidebar remain fixed even when users scroll down the page, while also maintaining responsiven ...

Disconnecting a Metamask Wallet in an Angular application: A Step-by-

I need assistance with disconnecting a Metamask wallet using web3 in Angular. //this is my wallet connection code async connectWallet() { const accounts = await this.ethereum.request({ method: 'eth_requestAccounts', }); this.selectedAddress ...

Looking to add a dynamic drop-down menu to my search bar, similar to Google search

Is there a way to create a dynamic drop-down list where, when a user enters the first letter of a country name, the list displays countries with names starting with that letter? It's similar to the functionality of a Google search bar. The country nam ...

Incorporating a HTML layout with a JS backdrop

I have successfully implemented a JavaScript background and now I want to apply this background across all my PHP files. The issue is that the HTML code either overlaps with the JS content or appears behind it. How can I resolve this? Below is the JS fil ...

Is it possible to populate an empty list of objects within the Page_Load scope after the page has finished loading?

I am facing a challenge where I need to populate the list var docfiles = new List<string>(); with file names uploaded by the user using dropzone js. However, the list remains empty because when the page loads for the first time, httpRequest.Files.C ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...

React Native tutorial: Changing button color on press

When a user clicks on the TouchableOpacity element, I want to change the color of the button from the default gray to blue. Initially, the 'checked={this.state.newProjects}' newProjects variable is not present in the state, so when clicked it sho ...

What is the exact functioning of the Array.push() method in Javascript?

During my online CS class, we covered the topic of how Arrays and memory work. The teacher used C as an example to explain that you cannot add extra elements to a full Array. As someone who started with JavaScript, I found it interesting that in JavaScript ...

Discovering the method to access a local function within a static function in Javascript ES6 (ES2015) or Typescript

Is there a way to access the non-static "foo2" method from inside the static "bar" method? So far, I'm only able to access the "foo1" and "foo3" methods. Can anyone provide guidance on how to achieve this? let foo1 = () => { alert('foo1†...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

When utilizing the data property within the useQuery() hook, an error may arise stating "Unable to

This problem has me scratching my head. The code snippet below is triggering this error: TypeError: Cannot read properties of undefined (reading 'map') When I use console.log() to check res.data, everything seems normal and there is data present ...

Prevent empty comments in Vue.js

Typically, Vue.js will insert a comment placeholder when hiding an element using v-if. Vue file: <div v-if="true">Hello</div> <div v-if="false">world</div> Output: <div v-if="true">Hello</div ...

Transferring information from a client-side JavaScript to a Node.js Express server and receiving back

I'm currently working on implementing an upvote and downvote system in nodejs. The functionality for upvoting and downvoting will be handled by client-side JavaScript, which will then send the data to the server for storage. I'm curious to know ...

The problem with setting headers in Node Express MySQL: Error message indicating headers cannot be set after they have been sent

I'm currently working on a project using Node.js, Express.js, and a MySQL database. I have posts stored in the database that I want to display using the Pug.js view engine. I've managed to connect to the database and render the home route success ...

Finding the Middle Point of a Circle Using CEP/JavaScript

Using a specific set of calculations, I am able to create a circle in this manner: var yMinCir = height - 1515.80/2.667+8.5; var yMaxCir = height - 1545.80/2.667+8.5; var myCircle = page.ovals.add({geometricBounds:[yMinCir, 1312.63/2.667+8.5, yMaxCir, 1342 ...

JavaScript library called "Error: JSON input ended unexpectedly"

I am currently operating a server using node.js and Express v4.0 Additionally, I am utilizing the request library. However, when receiving a response from the server, I encounter an Uncaught SyntaxError: Unexpected end of JSON input. The response I receiv ...