Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVASCRIPT: subtracting Time and getting its number of minutes

Tags:

javascript

For Example:

StartTime = '00:10';
EndTIme = '01:20';

These variables are string

Question: How can I Subtract them and returning the span time in minutes?

Hope you can help

like image 441
Treby Avatar asked Dec 22 '09 07:12

Treby


People also ask

How do you subtract time in JavaScript?

setHours(date. getHours() - numOfHours); return date; } // 👇️ Subtract 1 hour from the current date const result = subtractHours(1); // 👇️ Subtract 2 hours from another date const date = new Date('2022-04-27T08:30:10.820'); // 👇️ Wed Apr 27 2022 06:30:10 console.

How do you subtract minutes from time?

To subtract time, subtract the minutes then subtract the hours. Since we can't have negative minutes, add 60 to the minutes and subtract 1 from the hours (60 minutes = 1 hour).

How do you subtract minutes from epoch time?

The time is in millis-since-the-epoch, so to find out five minutes before you simply have to subtract 5 mins in milliseconds (5 * 60 * 1000).


2 Answers

Make a function to parse a string like that into minutes:

function parseTime(s) {
   var c = s.split(':');
   return parseInt(c[0]) * 60 + parseInt(c[1]);
}

Now you can parse the strings and just subtract:

var minutes = parseTime(EndTIme) - parseTime(StartTime);
like image 164
Guffa Avatar answered Sep 21 '22 14:09

Guffa


var startTime = "0:10";
var endTime = "1:20";

var s = startTime.split(':');
var e = endTime.split(':');

var end = new Date(0, 0, 0, parseInt(e[1], 10), parseInt(e[0], 10), 0);
var start = new Date(0, 0, 0, parseInt(s[1], 10), parseInt(s[0], 10), 0);

var elapsedMs = end-start;
var elapsedMinutes = elapsedMs / 1000 / 60;
like image 27
David Hedlund Avatar answered Sep 21 '22 14:09

David Hedlund