Calculating the time difference in seconds between two dates using JavaScript

I am working with dates stored in MongoDB as UTC using Date(), and the format looks like Mon, 02 Apr 2012 20:16:31 GMT.

My goal is to calculate the time difference in total seconds between this date and the current time (in UTC).

I attempted the following approach:

now = new Date();
current_date = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
end_date = obj.end_date (Mon, 02 Apr 2012 20:16:35 GMT);
d = new Date(end_date - current_date);
console.log(d.getSeconds());

However, the result shows 22 for seconds, which is incorrect.

This method also seems overly complex. Is there a more efficient way to achieve this either within MongoDB or using JavaScript?

Any suggestions or advice would be greatly appreciated - thank you!

Answer №1

To calculate the time difference in seconds between two Date objects, you can use the getTime() method to get the timestamps in milliseconds and then divide the difference by 1000.

For example:

const now = new Date();
const currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
const endDate = new Date(obj.end_date); // Assuming obj.end_date is in the format (Mon, 02 Apr 2012 20:16:35 GMT)
const millisDiff = endDate.getTime() - currentDate.getTime();
console.log(millisDiff / 1000);

Answer №2

(endDate.getTime() - currentDate.getTime()) / 1000

getSeconds() function will only give you the seconds component, excluding minutes and hours.

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

Loading excessive amounts of HTML onto a single webpage

Currently, I am involved in the creation of a HTML client for a collaborative game project. This client will require multiple scenes/pages such as the login, lobby, game page, and more. While I usually have no issue with page navigation, the client must ...

The evaluate function is not functioning as expected

Code: console.log(propertyName); console.log(eval(this.state.propertyName)) console.log(this.state.DriverFirstName); Output: DriverFirstName undefined fsdfds I am attempting to access a variable defined by a string value (propertyNa ...

Parsing JSON sub items in Android application using Java

Here is a snippet of my PHP file: <?php $myObj = array( "name"=>"John" , "age"=>"30" , "post"=>[ "title"=>"What is WordPress" , "excerpt"=>"WordPress is a popular blogging platform" , ...

endless cycle during the process of saving a record in a mongo collection

When making a POST request to an API to create a new message and then saving that message inside the user collection in the promise callback, I encountered a particular issue. This line is causing trouble - user.messages.push(result); //problem here ...

Using jQuery to animate an image with two buttons, causing it to shift horizontally from left to

My goal is to create a stickman picture that moves from left to right whenever I click on one of two buttons labeled "<" and ">". Here's the code snippet I have so far: function personLeft() { $('#img').animate({left:& ...

leveraging AJAX to showcase information retrieved from a MySQL database

Hello! I am brand new to PHP and have little knowledge of AJAX. I am in the process of creating a photo gallery site and have used the following code to display my photos. I would like to make it possible, using AJAX or any other language, for someone to c ...

GTM - Table - Press a button to extract the text from a different element

I am not a coder, but I'm diving into the world of Google Tag Manager with the aim of tracking button clicks on search results. I have clients who want to monitor interactions with specific products displayed in their search results. While setting up ...

The technique of accessing parent props from a child composition component in React

I am trying to reduce every letter prop from the child component, Palata. How can I achieve this? index.js <Block letter="I" mb={16}> <Palata letter="I" start={4} end={9}/> <Wall/> <Empty/> <Palata le ...

When a user clicks on a button, AJAX and jQuery work together to initiate a setInterval function that continually

Currently, I have two scripts in place. The first script is responsible for fetching a specific set of child nodes from an XML file through AJAX and using them to create a menu displayed as a list of buttons within #loadMe. What's remarkable about thi ...

How can I invoke a personalized function in angularjs from HTML?

One way to organize methods within js controllers is by defining them separately like this: angular.module('test').controller('mycontroller', mycontroller); function mycontroller() { //do something }; function ...

Concealing an iframe upon clicking an element

I'm facing an issue with an Iframe on my website. Currently, the Iframe is hidden and becomes visible after the load function finishes. This is done to ensure that any style changes made during loading, such as hiding certain elements and changing the ...

Exploration of the Vue filtering technique and its functionality

Below is the code I have tried: deleteAJobWithEvents(event){ const data = event.store.readQuery({ query: ClientJobsList, variables: {id:1} }); data.client.jobs.filter(job => job.id !== 101); console.log(data); ...

API for controlling a 360-degree video camera in Three.js

I have been exploring this demonstration: utilizing the given code snippet: let camera, scene, renderer; let isUserInteracting = false, lon = 0, lat = 0, phi = 0, theta = 0, onPointerDownPointerX = 0, ...

Tips for integrating Google WebKit with AngularJS

Looking to enhance my application with Google WebKit functionality. My goal is to create a feature similar to Gmail's where hovering over the "+" symbol expands to display options such as "insert photos" and "insert links". I'm just starting out ...

The collapse menu toggle feature seems to be malfunctioning, as it is not functioning properly

I've been working on a website at , where the toggle menu is causing the content to hide when the menu is expanded. <aside id="layout-menu" class="layout-menu menu-vertical menu bg-menu-theme active"> <div class= ...

utilize logger in external javascript modules

Recently, I have delved into nodejs and am still in the beginning stages of learning. During my journey, I came across a situation where I needed to instantiate a logger (Pino) in server.js, which serves as the entry point for my project. My goal was to e ...

Attempting to extract a text string from a chunk of HTML code

My goal is to extract a text string (specifically, an article title) from a snippet of HTML code. The title in question reads "Journalist Allegedly Spied on Zoom Meetings of Rivals in Hilariously Dumb Ways." The challenge lies in the fact that the title d ...

Utilizing a custom function to filter Firestore collection data based on location proximity

I have a question about filtering a Firestore collection using a function where the values of the documents in the collection are used as arguments. Let's say we have a Firestore collection with documents structured like this: { pointOfInterest: "S ...

Utilizing MongoDB Compass to examine schema and display geographical data using objects instead of arrays

I am currently working with MongoDB Compass version 1.26 and have several collections containing latitude and longitude data structured like this: "coordinates": { "latitude": "43.0818", "longitude": "-8 ...

Should await be used before dispatching hooks in redux?

I am facing a scenario where I need to execute 2 dispatch events consecutively, with no dependency between them. Could I implement it like the following code snippet? await dispatch(firstEvent) dispatch(secondEvent) My goal is to ensure that secondEvent ...