I have two time variables, in this format:
it prints this to console:
How would I get the time passed (in seconds) from the first line to the second one?
Thanks!
I have two time variables, in this format:
it prints this to console:
How would I get the time passed (in seconds) from the first line to the second one?
Thanks!
local str = "2024-11-24_03:01:07"
local str2 = "2024-11-27_03:01:11"
-- 1. Split the date and time parts
local date1, clocked1 = str:match("([^_]+)_(.+)") -- Get date and time from the string using regex
local date2, clocked2 = str2:match("([^_]+)_(.+)")
-- 2. Split clocked up in h, m, s for both times
local clocksplit1 = clocked1:split(":")
local clocksplit2 = clocked2:split(":")
local h1, m1, s1 = tonumber(clocksplit1[1]), tonumber(clocksplit1[2]), tonumber(clocksplit1[3])
local h2, m2, s2 = tonumber(clocksplit2[1]), tonumber(clocksplit2[2]), tonumber(clocksplit2[3])
-- 3. Parse the date (year, month, day)
local year1, month1, day1 = date1:match("(%d+)-(%d+)-(%d+)")
local year2, month2, day2 = date2:match("(%d+)-(%d+)-(%d+)")
-- Convert date and time to total seconds since epoch (1970-01-01), calculate seconds since epoch for a given date and time
local function date_to_seconds(year, month, day, hour, minute, second)
local t = os.time({year = year, month = month, day = day, hour = hour, min = minute, sec = second})
return t
end
-- 4. Convert both times (including dates) to total seconds since epoch
local time1_in_seconds = date_to_seconds(tonumber(year1), tonumber(month1), tonumber(day1), h1, m1, s1)
local time2_in_seconds = date_to_seconds(tonumber(year2), tonumber(month2), tonumber(day2), h2, m2, s2)
-- 5. Calculate the difference in seconds
local difference_in_seconds = time2_in_seconds - time1_in_seconds
-- 6. Output the difference
print("Time difference in seconds:", difference_in_seconds)
Use unix timestamp instead and subtract the start time from the current time to get the duration between the two. Then convert the timestamp into some other format.
What is unix timestamp? What would that look like? Thanks!
@ExercitusMortem posted the solution youâre interested in.
What motivates people like this dude to read questions and proceed to write hugely useful code examples is beyond me.
Some language model? I donât want to accuse someone without further proof, or devalue someoneâs work, but every word is capitalized correctly everywhere, and the line âepoch (1970-01-01)
â doesnât seem like itâs from a human⌠But thatâs only an assumption, not an accusation.
âEpochâ is just what UNIX 0 is referred to; if youâve never seen that word before Iâd recommend a dictionary.
yes, I know what that is, itâs just super unusual that someone would be so descriptive. Or maybe Iâm just being dumb. Either way, it works, all good :D