Page 1 of 1
Parsing Time String: 'HH:MM:SS'
Posted: Sat Mar 06, 2021 8:28 am
by jkgarner
Has anybody got a code snippet that parses the time string 'HH:MM:SS'?
While, simply parsing the number out would be useful, and I would be grateful for even that, I really could use one that returns the time as a timestamp, which assumes current day.
I could take a bit of time to write one, but why reinvent the wheel?
I've got a lot of other code to write, specifically test code for what I've already written.
Since I am writing test code, does that mean I'm 'righting' my other code? [:D]
RE: Parsing Time String: 'HH:MM:SS'
Posted: Sat Mar 06, 2021 8:59 pm
by KnightHawk75
On the simple parse I'm sure there is easier way using string.match or gmatch but this one is handy for simple split function.
Code: Select all
local str1 = "23:01:01"
gKH={}
gKH.base={}
----------
-- These next two via Jack Taylor https://stackoverflow.com/questions/1426954/split-string-in-lua
----------
-- gsplit: iterate over substrings in a string separated by a pattern
--
-- Parameters:
-- text (string) - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean) - if true (or truthy), pattern is interpreted as a plain
-- string, not a Lua pattern
--
-- Returns: iterator
--
-- Usage:
-- for substr in gsplit(text, pattern, plain) do
-- doSomething(substr)
-- end
Code: Select all
function gKH.base:gsplit(text, pattern, plain)
local splitStart, length = 1, #text
return function ()
if splitStart then
local sepStart, sepEnd = string.find(text, pattern, splitStart, plain)
local ret
if not sepStart then
ret = string.sub(text, splitStart)
splitStart = nil
elseif sepEnd < sepStart then
-- Empty separator!
ret = string.sub(text, splitStart, sepStart)
if sepStart < length then
splitStart = sepStart + 1
else
splitStart = nil
end
else
ret = sepStart > splitStart and string.sub(text, splitStart, sepStart - 1) or ''
splitStart = sepEnd + 1
end
return ret
end
end
end
Code: Select all
-- split: split a string into substrings separated by a pattern.
--
-- Parameters:
-- text (string) - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean) - if true (or truthy), pattern is interpreted as a plain
-- string, not a Lua pattern
--
-- Returns: table (a sequence table containing the substrings)
function gKH:split(text, pattern, plain)
local ret = {}
for match in gKH.base:gsplit(text, pattern, plain) do
table.insert(ret, match)
end
return ret
end
local retval = gKH:split(str1,":",true);
print(retval); -- use data as needed.
RE: Parsing Time String: 'HH:MM:SS'
Posted: Mon Mar 08, 2021 7:07 pm
by jkgarner
Thanks. I have a split string function, so I used that.