UmbDK
UmbDK

Reputation: 13

Subtracting two times to give total minutes in javascript (non standard time format)

I need to take two times and subtract them to give me the total minutes. (DST and over 24 hour period not required). However, I am not using a standard "time" format, ie the ":" is not used, just 4 digits: 1150 instead of 11:50. For example:

The Start time is 1150 The End time is 1205

If I do a simple subtract, the value would be 55, not 15.

It also needs to work if the two times do not cross into the next hour, ie 1105 and 1125.

TYIA

Upvotes: 1

Views: 33

Answers (2)

Kosh
Kosh

Reputation: 18434

You can use the following math:

let [start, end] = [1150, 1205]
const to_minutes = (t) => 60*(t/100|0)+t%100
console.log(to_minutes(end) - to_minutes(start))

Upvotes: 0

Ashar Dweedar
Ashar Dweedar

Reputation: 643

try :

var t1 = 1150
t1H = parseInt((t1+"").substring(0,2))
t1M = parseInt((t1+"").substring(2,4)) + t1H * 60

var t2 = 1205
t2H = parseInt((t2+"").substring(0,2))
t2M = parseInt((t2+"").substring(2,4)) + t2H * 60

var res = t2M - t1M;

Upvotes: 1

Related Questions