How can I get the minute difference between 2 times?
Let’s say 16:21 and 18:54, or even 23:30 and 04:34
It must work between different days (like the second example)
I could not come with a method to do this, any ideas?
How can I get the minute difference between 2 times?
Let’s say 16:21 and 18:54, or even 23:30 and 04:34
It must work between different days (like the second example)
I could not come with a method to do this, any ideas?
you would have to use os.time and minus or divide their hours or minutes or seconds
minus the first and second time, then divide it by 60.
eg.
local time1 = 1000
local time2 = 250
local timeInSeconds = time1 - time2
local timeInMins = timeInSeconds/60
Let’s call the hours of each time Hours1 and Hours2. Let’s call the minute of each time Mins1 and Mins2.
local MinsDiff = Mins2 - Mins1
local HoursDiff = Hours2 - Hours1 - ( math.sign( MinsDiff ) < 0 and 1 or 0 )
local MinutesBetween = MinsDiff % 60 + ( HoursDiff % 24 ) * 60
You can get the hours and minutes parts using substrings (string.sub). Check the docs for how to use it. And use tonumber to convert to a number.
Edit: Not sure why it was worded like this when you needed HH:MM format, regardless it can still be tweaked to work with that.
local time1 = "0:00" -- means 60 minutes
local time2 = "16:00"
local function getMinuteDifference(t1, t2) -- get's difference between time1 and time2, time1 has to be greater
local m1, m2 = t1:split(":")[1], t2:split(":")[1]
if m1 < m2 then t1 = (m1 + 60)..":"..t1:sub(4) end
local t, minutes = {t1, t2}, {}
for i = 1, 2 do
table.insert(minutes, t[i]:split(":")[1] + (t[i]:split(":")[2]/60))
end
return (minutes[1] - minutes[2]), " minutes difference"
end
print(getMinuteDifference(time1, time2))
“01:10” would mean 60 minutes + 1 minute + 10 seconds, “10:10” would mean 10 minutes and 10 seconds.
Likely there’s simpler calculation.
I think OP is after the usual time format of HH:MM not MM:SS as your code would suggest. A couple tweaks to use 24 instead of 60 for the rollover and multiplying the stuff before the colon by 60 instead of dividing the stuff after the colon by 60 should do the trick.
Also don’t forget to sort out your indentation. It wasn’t immediately clear it was all inside of a function due to the indentation.