PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 6ms RepoModel.GetById 34ms 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
 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
14-module(ewgi_util_calendar).
15-author('Hunter Morris <hunter.morris@smarkets.com>').
16
17-define(UNIX_EPOCH, {{1970,1,1},{0,0,0}}).
18
19-include("ewgi.hrl").
20
21-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]).
22
23%% @spec now_to_unix_ts() -> integer()
24%% @doc Gives the current UNIX timestamp.
25-spec now_to_unix_ts() -> non_neg_integer().
26now_to_unix_ts() ->
27    now_to_unix_ts(calendar:now_to_universal_time(erlang:now())).
28
29%% @spec now_to_unix_ts(calendar:t_datetime1970()) -> integer()
30%% @doc Gives the UNIX timestamp for the corresponding time value.
31-spec now_to_unix_ts(calendar:t_datetime1970()) -> non_neg_integer().
32now_to_unix_ts(Tm) ->
33    calendar:datetime_to_gregorian_seconds(Tm) -
34        calendar:datetime_to_gregorian_seconds(?UNIX_EPOCH).
35
36%% @spec now_to_unix_ts(calendar:t_datetime1970(), non_neg_integer()) -> float()
37%% @doc Gives the current UNIX timestamp with fractional microseconds.
38-spec now_to_unix_ts(calendar:t_datetime1970(), non_neg_integer()) -> float().
39now_to_unix_ts(Tm, 0) ->
40    now_to_unix_ts(Tm);
41now_to_unix_ts(Tm, Ms) when is_integer(Ms) ->
42    now_to_unix_ts(Tm) + (Ms / 1000000).
43
44%% @spec now_utc_ms() -> {calendar:t_datetime1970(), non_neg_integer()}
45%% @doc Gives a tuple representing the current UNIX timestamp and microseconds.
46-spec now_utc_ms() -> {calendar:t_datetime1970(), non_neg_integer()}.
47now_utc_ms() ->
48    {_, _, Ms} = Now = erlang:now(),
49    {calendar:now_to_universal_time(Now), Ms}.
50
51%% @spec now_utc_ts_ms() -> integer()
52%% @doc Gives the number of milliseconds since the UNIX epoch.
53-spec now_utc_ts_ms() -> integer().
54now_utc_ts_ms() ->
55    {Tm, Ms} = now_utc_ms(),
56    now_to_unix_ts(Tm) * 1000 + round(Ms / 1000).