1

I have file names encoded with datetimes in the format:yyyy-mm-dd_HHhMMhSSs.
Real example: 2013-08-05_15h44m28s (in the time portion, it can have only the hour part)

I have to convert it back to an actual datetime. The date part is so easy that it's already solved, but for the time portion I didn't found in my delphi install a way to do that out-of-the-box.

So I got an SScanf implementation to solve that, but the question remains: did I overlook something or it's indeed the way to do that without having to write code myself?

Note: although I tagged my delphi version, functions that exist in more recent versions are interesting too.
BTW, someone knows if that formatting of the time portion have an name?

Fabricio Araujo
  • 3,810
  • 3
  • 28
  • 43

1 Answers1

3

This is a good use case for a regex. Once you pulled off the date then you can use this regex:

(\d+)h(\d+)m(\d+)s

In fact, you may as well parse the entire string that way. All you need is this function:

function ToDateTime(const str: string): TDateTime;
var
  Match: TMatch;
begin
  Match := TRegEx.Match(str, '(\d+)-(\d+)-(\d+)_(\d+)h(\d+)m(\d+)s');
  if Match.Groups.Count<>7 then
    raise Exception.CreateFmt('Could not parse date/time: %s', [str]);
  Result := EncodeDateTime(
    StrToInt(Match.Groups[1].Value),
    StrToInt(Match.Groups[2].Value),
    StrToInt(Match.Groups[3].Value),
    StrToInt(Match.Groups[4].Value),
    StrToInt(Match.Groups[5].Value),
    StrToInt(Match.Groups[6].Value),
    0
  );
end;
HeartWare
  • 7,464
  • 2
  • 26
  • 30
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490