Browse Source

add datetime functions

Yuriy Zhloba 10 years ago
parent
commit
061ede1ca9
3 changed files with 57 additions and 1 deletions
  1. 11 0
      include/herd.hrl
  2. 45 0
      src/herd_datetime.erl
  3. 1 1
      src/herd_simple_formats.erl

+ 11 - 0
include/herd.hrl

@@ -0,0 +1,11 @@
+-type(timestamp() :: integer()).
+-type(timestamp_micro() :: float()).
+
+%% jiffy json format
+-type(json_key() :: atom() | binary()).
+-type(json_value() :: integer() | float() | binary() | json_obj() | [json_value()]).
+-type(json_obj() :: {[{json_key(), json_value()}]}).
+
+
+%% PostgreSQL returns datetime like this: 2014-12-20 17:38:56.475565+03
+-type(db_datetime() :: {calendar:date(), {0..23, 0..59, float()}}).

+ 45 - 0
src/herd_datetime.erl

@@ -0,0 +1,45 @@
+-module(herd_datetime).
+
+-export([now/0, now_micro/0,
+         datetime_from_db/1,
+         timestamp_to_datetime/1, datetime_to_timestamp/1,
+         datetime_to_ISO/1]).
+
+-include("herd.hrl").
+
+
+%%% module API
+
+-spec now() -> timestamp().
+now() ->
+    {Mega, Sec, _Micro} = erlang:now(),
+    Mega * 1000000 + Sec.
+
+
+-spec now_micro() -> timestamp_micro().
+now_micro() ->
+    {Mega, Sec, Micro} = erlang:now(),
+    Mega * 1000000 + Sec + Micro * 1.0e-6.
+
+
+-spec datetime_from_db(db_datetime()) -> calendar:datetime().
+datetime_from_db({Date, {Hour, Minute, Second}}) ->
+    {Date, {Hour, Minute, round(Second)}}.
+
+
+-spec timestamp_to_datetime(timestamp() | timestamp_micro()) -> calendar:datetime().
+timestamp_to_datetime(Timestamp) ->
+    calendar:now_to_universal_time({Timestamp div 1000000, Timestamp rem 1000000, 0}).
+
+
+-spec datetime_to_timestamp(calendar:datetime()) -> timestamp().
+datetime_to_timestamp(DateTime) ->
+    % 62167219200 == calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})
+    calendar:datetime_to_gregorian_seconds(DateTime) - 62167219200.
+
+
+-spec datetime_to_ISO(calendar:datetime()) -> string().
+datetime_to_ISO({{Year, Month, Day}, {Hour, Minute, Second}}) ->
+    lists:flatten(
+        io_lib:format("~4..0b-~2..0b-~2..0bT~2..0b:~2..0b:~2..0b",
+                      [Year, Month, Day, Hour, Minute, trunc(Second)])).

+ 1 - 1
src/herd_simple_formats.erl

@@ -27,7 +27,7 @@ get_time(Str) ->
     end.
     end.
 
 
 
 
--spec get_datetime(string()) -> calendar:datetime().
+-spec get_datetime(string()) -> calendar:datetime() | error.
 get_datetime(Str) ->
 get_datetime(Str) ->
     case string:tokens(Str, " ") of
     case string:tokens(Str, " ") of
         [DStr, TStr | _] ->
         [DStr, TStr | _] ->