What is the accurate way to determine the total number of minutes elapsed from a specific point in time?

String representation of the process start date:

'2020-03-02 06:49:05'

Process completion date:

'2020-03-02 07:05:02'

Question:
What is the optimal method for calculating the time difference (in minutes) between the start and end of the process? (Any suggestions on built-in methods in vue.js or nuxt.js would also be greatly appreciated.)

Answer №1

In my opinion, utilizing the JavaScript Date object is the most effective approach for this task.

const startTime = '2020-03-02 06:49:05';
const endTime = '2020-03-02 07:05:02';

const timeDifferenceInMilliseconds = Math.abs(new Date(startTime) - new Date(endTime));
const timeDifferenceInMinutes = timeDifferenceInMilliseconds / 60000;

Answer №2

One great library you could consider using is Moment.js. Here's an example of how you can use it:

var timeDifference = moment.duration(endTime.diff(startTime));
var totalMinutes = timeDifference.minutes();

If you want to learn more about durations in Moment.js, you can check out their documentation here.

Answer №3

Using Date.parse(), you can create a date object from a string and then calculate the difference in minutes.

Here's an example:

const startTime= Date.parse('2020-03-02 06:49:05')
const endTime = Date.parse('2020-03-02 07:05:02')

// Difference in Minutes
const durationInMin= (endTime-startTime)/60000;

console.log({ startTime, endTime, durationInMin })

alert(`Process took: ${durationInMin} minutes`)

If you need human-readable dates, consider using date-fns, which is lightweight compared to momentjs.

import { differenceInMinutes } from 'date-fns';

const startDate = '2020-03-02 06:49:05';
const endDate = '2020-03-02 07:05:02';
const durationInMin = differenceInMinutes(new Date(endDate), new Date(startDate));

console.log(`Duration: ${durationInMin} minutes`);

Adding another dependency may increase project size, but if you deal with many human-readable dates, it could be beneficial.

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

When pressing the next or previous button on the slider, an error message pops up saying "$curr[action] is not a

I found this interesting Js fiddle that I am currently following: http://jsfiddle.net/ryt3nu1v/10/ This is my current result: https://i.sstatic.net/VygSy.png My project involves creating a slider to display different ages from an array, such as 15, 25, ...

What is the correct way to define a function parameter when using AngularJS Emit?

I've been exploring the emit feature in AngularJS and had a question about passing a function as an argument. In the Parent Controller: $scope.$on("getChildFunction", function(event, func) { console.log("The function is...", func); }) In the Ch ...

Turning a text into a JSON data structure

How can I make JavaScript recognize a string as JSON? I have a function that only works when passed a JSON object. If I pass a string with the same format as JSON, it doesn't work. I want to find a way for the function to treat the string as JSON, ev ...

I am encountering an issue with my function where I aim to prevent the creation of a node using duplicate coordinates

Trying to avoid creating a node with existing coordinates, I implemented a check in my code. The check is supposed to determine if there are any nodes with the same coordinates already present. However, it seems that the check is not working as expected an ...

What is the purpose of using async/await in Node.js when it is inherently asynchronous, and in JavaScript as well, vice versa?

Apologies for my lack of experience in Javascript and NodeJS. I'm a total beginner, so please excuse my silly questions. I've been trying to wrap my head around the concept but haven't found a clear explanation. Here's what's conf ...

Terser is causing ng build --prod to fail

When I run ng build --prod on my Angular 7 application (which includes a C# app on the BE), I encounter the following error: ERROR in scripts.db02b1660e4ae815041b.js from Terser Unexpected token: keyword (var) [scripts.db02b1660e4ae815041b.js:5,8] It see ...

Perform batch updates on multiple documents using MongoDB

How can I efficiently update multiple documents in MongoDB by iterating through an array of objects and then returning the modified documents in the response? Be sure to refer to the code comments for guidance .put(function (req, res) { var data = r ...

How to Access a div from another website using jQuery

I have a question. How can I call a div from another website using JavaScript? Here is the page: Now, I want to call the <div id="testa"> in another page. The other page is called Otherpage.html: jQuery(function($){ $(&ap ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

Executing multiple MSSQL queries in a Node.js environment

Currently, I am faced with the challenge of running multiple SQL queries. The issue lies in variables going out of scope due to the asynchronous nature of node.js. I am attempting to find a solution similar to the await keyword available in C#. To clarif ...

Generate listview items containing anchor tags automatically

I am currently developing a web application using Jquery Mobile. After retrieving data from a webservice function, I am utilizing an ajax call to display this data on my webpage. $('[data-role=page]').on('pageshow', function () { var u ...

What is the best way to send information using AJAX when combining a form submission with a global variable?

I'm currently working on a project where I need to upload a file to my server and save the filename to my database. Although I've successfully saved it to the database, I also want to save the username along with the filename. The issue is that I ...

Disabling 'Input Number' feature is ineffective in Firefox browser

Is there a way to prevent the input value from changing when the up or down arrow is held, even if the input is disabled? I want to retain the arrows without allowing this behavior on Firefox. Give it a try: Press the up arrow. After 5 seconds, the input ...

Retrieve information from MongoDB using a custom date string in Javascript

As a newcomer to NodeJS, I have a MongoDB collection that stores the following Data: [{ _id: new ObjectId("6180c67a9b414de991a24c43"), cusDate: '20/11/2021 03:32 AM', cusName: 'Akila', cusEmail: ...

How can I effectively display a blank menu item for the SelectField component in Material-UI within a React application?

I am using the select-field component from the material-ui framework version 0.15.4 with React version 15.4.0. I am attempting to add a blank menu-item to the select-field in order to allow for deselecting a value in the dropdown field when clicked. Howeve ...

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

Using dynamic colors in Vue.js

I'm currently trying to bind multiple colors to a spinner component, but I'm facing some difficulties with it and my mind is starting to feel a bit foggy. Below is the spinner component itself, bound to a computed value. <fingerprint-spinner ...

How can I change the background color of the initial word in a textbox?

In my HTML, I have a text box input. While I am familiar with how to use CSS to set the background color of the entire textbox using background-color, I am wondering if it is possible to specifically target and change the background color of only the first ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

What is the best method to change the value of a nearby TD text box?

I am currently developing a shopping cart application that requires me to update product screens based on users' previous orders stored as local JSON data. The product screen is built using JSON returned from the server. My goal now is to automatical ...