JavaScript Function for Finding the Time Difference Between Two Dates (in Years, Days, Hours, or Less than One Hour)

I need to calculate the time difference between 2 dates and display it. If the difference is greater than a year, show the number of years only. If it's more than a day, show the number of days. If it's less than a day, show the number of hours. If it's less than an hour, display "You have less than one hour left."

One possible solution is to utilize Moment.js:

remainingTime() {
  moment.locale('fr_FR');
  return moment(new Date(this.finishedAt)).from(new Date(this.startedAt));
}

However, this method might not give the exact result if the remaining time is less than a day.

How can we achieve accurate results using native JavaScript or Moment.js for calculating the time difference?

Answer №1

Using vanilla JavaScript, achieving this task is quite straightforward. Keep in mind that dates are measured in milliseconds, allowing you to easily perform mathematical operations on them.

const findDateDifference = (startDate, endDate) => endDate - startDate;

You can create a function to calculate the difference in seconds (60), minutes (3600), hours (86400), months, and years—taking into account conditions for leap years and varying month lengths—and then return the appropriate result based on your specific requirements.

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

Creating a sidebar that remains fixed in place even as the page is scrolled down can be achieved by using CSS and positioning properties

I am looking to create a website with a specific layout design as shown in this image: https://i.stack.imgur.com/ndKcz.png The main focus is on making the sidebar (F/T container) function as a social network link, sticking to the right side of the page ev ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

Retrieve the visible text content of an element by utilizing various ids

I am currently working on a project using AngularJS with multiple conditions all sharing the same id. My goal is to extract text only from the condition that evaluates to true. Recently, I discovered a major bug in an app that I am preparing for release. ...

What is the best way to automatically create a PDF file that includes interactive JavaScript charts?

My goal is to create a word document or PDF containing charts from various JavaScript chart libraries. I've successfully implemented these libraries on websites, but now I want to include them in my documents as well. My initial attempt involved usin ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Is it possible to modify a JavaScript array variable without having to refresh the page by utilizing Ajax?

Is it possible to update a JavaScript array variable without having to reload or refresh the page? I have an existing list of data in an array, and I retrieve additional data using PHP and Ajax. Now I want to add the new data obtained from PHP Ajax to th ...

Transferring data files through an ajax-based form submission

I am encountering an issue when trying to send a file to a server using AJAX for submission. Despite attempting various methods involving var xhr = new XMLHttpRequest(); and $.ajax({});, I consistently receive the error message Uncaught TypeError: Illegal ...

Ajax - Retrieving data from a different webpage

My index.php contains the following HTML: <div id="showDetails"> </div> <div id="showList"> </div> And this Ajax function is also in index.php: function ...

nodemon was not properly installed on the system

I attempted to add nodemon to my application using the command below: npm install nodemon -g This is the output that was generated: changed 116 packages, and audited 117 packages in 8s 16 packages are looking for funding run `npm fund` for details fou ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...

Processing JSON in PHP after an AJAX POST request

In the scenario where JavaScript is used to make an ajax request: index.js- var dataFeedback = $("#feedback_popup_message_body").val(); var jsonObj = JSON.stringify({dataFeedback: dataFeedback}); $.ajax({ url: "index.php", type: 'POST' ...

Emphasize entries in an index that match the currently visible content as you scroll

I have a table of contents in my HTML page with the CSS attribute position: fixed;. I want to emphasize the current reading position by highlighting it (bold or italics) as I scroll down the page. | yada yada yada ... 1. Secti ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

What is the method for adding a tag within a specific div ID in ExtJS?

I am looking to insert a new tag within existing tags using extjs, based on the div id 'task123', and also trigger an alert message accordingly. Below is the HTML code snippet: <div id="task123"> <div class="msg" id="sample"> ...

Creating a web form with HTML and integrating it with jQuery AJAX

Looking to fetch data from the server through jQuery AJAX on an HTML form and store the response in a PHP string variable. Here is my current code snippet: <form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe"> &l ...

What is the solution for addressing the absence of an 'Access-Control-Allow-Origin' header in the requested resource while using axios?

Here is my Vue script: <script> export default { ... methods : { login() { // uri -> http://my-app.test/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472b28202e2978222a262e2b7a332234330720 ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...

"Utilizing the Image onLoad event in isomorphic/universal React: Activating event registration once the image has been

When a page is rendered isomorphically, the image can be downloaded before the main script.js file. This means that the image may already be loaded before the react register's the onLoad event, resulting in the event never being triggered. script.js ...

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...