How to correctly calculate the number of minutes from a certain moment?

Viewed 340

There is a start date for the process in string form:

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

And the process completion date:

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

Question:
What is the most correct way from the point of view of the approach - to calculate the difference (in minutes) between the start and finish of the process? (if there are any built-in methods for this in vue.js ornuxt.js, it will be very interesting to learn about them as well.)

3 Answers

I think the best way would be to use Javascript Date object,

d1 = '2020-03-02 06:49:05'
d2 = '2020-03-02 07:05:02'

diff_in_millis = Math.abs(new Date(d1) - new Date(d2))
diff_in_minutes = diff/60000

I suggest using momentjs, you can do something like this:

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

More about duration in momentjs can be found here

Create the date from the string using Date.parse(). It return the date in milliseconds, get the difference and convert that to Minutes.

See snippet below.

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`)


Note: For human readable dates, I have found date-fns to be the most helpful. Given its lightweight compared to momentjs. And you could complete the same with the following.

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`);

At the cost of another dependence to the project of course, but if you are handling lots of human readable dates, it's worth it.

Related