Reputation: 1362
How to get following DateTime in Erlang?
Fri Jul 13 19:12:59 IST 2018
Upvotes: 0
Views: 1269
Reputation: 1
date_time() ->
{{Year, Month, Day},{ Hour, Minute, Second}} = calendar:local_time(),
DayOfWeek = calendar:day_of_the_week({Year, Month, Day}),
DayName = day_check(DayOfWeek),
MonthName = month_check(Month),
lists:flatten(io_lib:format("~3..0s ~3..0s ~2..0w ~2..0w:~2..0w:~2..0w IST ~4..0w", [DayName, MonthName, Day, Hour, Minute, Second, Year])).
day_check(1) -> 'Mon';
day_check(2) -> 'Tue';
day_check(3) -> 'Wed';
day_check(4) -> 'Thu';
day_check(5) -> 'Fri';
day_check(6) -> 'Sat';
day_check(7) -> 'Sun'.
month_check(1) -> 'Jan';
month_check(2) -> 'Feb';
month_check(3) -> 'Mar';
month_check(4) -> 'Apr';
month_check(5) -> 'May';
month_check(6) -> 'Jun';
month_check(7) -> 'Jul';
month_check(8) -> 'Aug';
month_check(9) -> 'Sep';
month_check(10) -> 'Oct';
month_check(11) -> 'Nov';
month_check(12) -> 'Dec'.
Upvotes: 0
Reputation: 1362
I found the solution.
A = calendar:universal_time().
qdate:to_string(<<"D M j G:i:s T Y">> , <<"IST">>, A).
You can use https://www.php.net/manual/en/function.date.php for different formatting. Advisable to use only if you have to support legacy system because this function call use seems expensive.
Upvotes: 0
Reputation:
TL; DR
Use the exceptional qdate
for all your date/time formatting, converting, and timezone handling. Look at the Demonstration section in particular to get the gist, and adjust to your needs.
Erlang's date handling, in my opinion, is convoluted and lacking in the major functionality that's needed for proper date handling. It's getting better, but not quite there. Moreover, timezone handling is primitive at best.
qdate
's functions will take (almost) any date format and convert to any date format, while using either an implicit timezone (setting the timezone on a per-process basis), or by setting a specific timezone.
In any case, if you go custom, you will end up with something similar to this:
1> {{Year, Month, Day}, {Hour, Minute, Second}} = calendar:now_to_datetime(erlang:now()).
{{2018,7,13},{14,39,45}}
2> lists:flatten(io_lib:format("~4..0w-~2..0w-~2..0wT~2..0w:~2..0w:~2..0w",[Year,Month,Day,Hour,Minute,Second])).
"2018-07-13T14:39:45"
...not good ;)
Those are my two cents. Cheers!
Upvotes: 3