PageRenderTime 40ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/utils/ewgi_util_calendar.erl

http://github.com/skarab/ewgi
Erlang | 56 lines | 25 code | 9 blank | 22 comment | 0 complexity | cc6dc3f4715fc7a6168a70d459fd5cf5 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. %% @author Hunter Morris <hunter.morris@smarkets.com>
  2. %% @copyright 2009 Smarkets Limited.
  3. %%
  4. %% @doc Smak date/time methods.
  5. %% @end
  6. %%
  7. %% Licensed under the MIT license:
  8. %% http://www.opensource.org/licenses/mit-license.php
  9. %%
  10. %% Some code is based on the Python Paste Project which is copyright Ian
  11. %% Bicking, Clark C. Evans, and contributors and released under the MIT
  12. %% license. See: http://pythonpaste.org/
  13. -module(ewgi_util_calendar).
  14. -author('Hunter Morris <hunter.morris@smarkets.com>').
  15. -define(UNIX_EPOCH, {{1970,1,1},{0,0,0}}).
  16. -include("ewgi.hrl").
  17. -export([now_to_unix_ts/0, now_to_unix_ts/1, now_to_unix_ts/2, now_utc_ms/0, now_utc_ts_ms/0]).
  18. %% @spec now_to_unix_ts() -> integer()
  19. %% @doc Gives the current UNIX timestamp.
  20. -spec now_to_unix_ts() -> non_neg_integer().
  21. now_to_unix_ts() ->
  22. now_to_unix_ts(calendar:now_to_universal_time(erlang:now())).
  23. %% @spec now_to_unix_ts(calendar:t_datetime1970()) -> integer()
  24. %% @doc Gives the UNIX timestamp for the corresponding time value.
  25. -spec now_to_unix_ts(calendar:t_datetime1970()) -> non_neg_integer().
  26. now_to_unix_ts(Tm) ->
  27. calendar:datetime_to_gregorian_seconds(Tm) -
  28. calendar:datetime_to_gregorian_seconds(?UNIX_EPOCH).
  29. %% @spec now_to_unix_ts(calendar:t_datetime1970(), non_neg_integer()) -> float()
  30. %% @doc Gives the current UNIX timestamp with fractional microseconds.
  31. -spec now_to_unix_ts(calendar:t_datetime1970(), non_neg_integer()) -> float().
  32. now_to_unix_ts(Tm, 0) ->
  33. now_to_unix_ts(Tm);
  34. now_to_unix_ts(Tm, Ms) when is_integer(Ms) ->
  35. now_to_unix_ts(Tm) + (Ms / 1000000).
  36. %% @spec now_utc_ms() -> {calendar:t_datetime1970(), non_neg_integer()}
  37. %% @doc Gives a tuple representing the current UNIX timestamp and microseconds.
  38. -spec now_utc_ms() -> {calendar:t_datetime1970(), non_neg_integer()}.
  39. now_utc_ms() ->
  40. {_, _, Ms} = Now = erlang:now(),
  41. {calendar:now_to_universal_time(Now), Ms}.
  42. %% @spec now_utc_ts_ms() -> integer()
  43. %% @doc Gives the number of milliseconds since the UNIX epoch.
  44. -spec now_utc_ts_ms() -> integer().
  45. now_utc_ts_ms() ->
  46. {Tm, Ms} = now_utc_ms(),
  47. now_to_unix_ts(Tm) * 1000 + round(Ms / 1000).