[erlang-questions] timestamp conversion
Jachym Holecek
freza@REDACTED
Sat Apr 16 00:53:49 CEST 2011
# Peter W. Morreale 2011-04-15:
> This may be embarrassingly simple, but I am struggling with it...
>
> I need compare string timestamps for dealing with expiration. In some
> cases it may another string timestamp, in others it will be against the
> current time.
>
> The string timestamps will always have the format:
>
> Year-Month-DayTHour:Min:SecZ"
>
> I think I want to convert to integer seconds, however even then its not
> clear to me how to perform the comparison, although I think this is a
> case for using the "if" expression.
>
> Please be gentle, I'm still new to Erlang.
Well, if all the fields are fixed width and taking final 'Z' to mean UTC [1],
you can just compare the strings, it will happen to work just the way you
want. :-) Try it in the shell to convince yourself.
More generally, you can easily [2] parse the string into datetime, which has
the form {{Year, Month, Day}, {Hour, Min, Sec}}, and then use functions in
calendar module (erl -man calendar) to convert that to gregorian seconds;
that's a simple (and large) integer suitable for comparisons and distance
calculations. For obtaining current timestamp you can use erlang:universaltime()
or now(), depends if on the resolution you need.
As to performing the comparison itself, you can do:
case T2 >= T1 of
true ->
expire(Thing);
_ ->
keep(Thing)
end
or
if T2 >= T1 ->
expire(Thing);
true ->
keep(Thing)
end
or
maybe_expire(T2, T1, Thing)
where
maybe_expire(T2, T1, Thing) when T2 >= T1 ->
expire(Thing);
maybe_expire(_, _, Thing) ->
keep(Thing).
In all of these, T1 and T2 are timestamps and their representation depends
on the conditions above. 'Thing', expire/1 and keep/1 have just intuitive
meaning.
HTH,
-- Jachym
[1] For nitpicks: and assuming characters codes for 0-9 sort in natural order.
[2] Assuming fixed fields widths, this goes like (completely untested):
string_to_datetime([Y1, Y2, Y3, Y4, $-, M1, M2, $-, D1, D2, $T, H1, H2, $:, N1, N2, $:, S1, S2, $Z]) ->
Date = {list_to_integer([Y1, Y2, Y3, Y4]), list_to_integer([M1, M2]), list_to_integer([D1, D2])},
Time = {list_to_integer([H1, H2]), list_to_integer([N1, N2]), list_to_integer([S1, S2])},
{Date, Time}.
If field widths aren't fixed, it's still simple but a bit tedious -- ask if you
need it (and don't forget to subject the person feeding you dodgy timestamps to
great pain in that case!).
More information about the erlang-questions
mailing list