Skip to content

Commit

Permalink
[4.3] Add previous_day method to kz_date (#6383)
Browse files Browse the repository at this point in the history
* Add previous_day method to kz_date
    kz_date:previous_day/1 will correctly handle month/year boundries
when calculating the previous day

* add some leap-year tests
  • Loading branch information
mark2600 authored Mar 17, 2020
1 parent c7be121 commit da74aa7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
16 changes: 16 additions & 0 deletions core/kazoo_stdlib/src/kz_date.erl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
,to_iso_week/1

,find_next_weekday/2
,previous_day/1
,normalize/1
,relative_difference/2

Expand Down Expand Up @@ -132,6 +133,21 @@ find_next_weekday({Y, M, D}, Weekday) ->
normalize({Y, M, D + ( 7 - DOW ) + RefDOW})
end.

%%------------------------------------------------------------------------------
%% @doc Calculates the date of the previous day, while also handling the situation
%% where that day falls on the previous month or previous year.
%% @end
%%------------------------------------------------------------------------------
-spec previous_day(kz_time:date()) -> kz_time:date().
previous_day({Y, 1, 1}) ->
{Y-1, 12, days_in_month(Y-1, 12)};

previous_day({Y, M, 1}) ->
{Y, M-1, days_in_month(Y, M-1)};

previous_day({Y, M, D}) ->
{Y, M, D-1}.

-spec from_iso8601(binary()) -> kz_time:date() | 'error'.
from_iso8601(<<Year:4/binary, Month:2/binary, Day:2/binary>>) ->
{kz_term:to_integer(Year), kz_term:to_integer(Month), kz_term:to_integer(Day)};
Expand Down
8 changes: 8 additions & 0 deletions core/kazoo_stdlib/test/kz_date_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@

-include_lib("eunit/include/eunit.hrl").

prev_date_test_() ->
[?_assertEqual({2020,02,02}, kz_date:previous_day({2020,02,03}))
,?_assertEqual({2020,01,31}, kz_date:previous_day({2020,02,01}))
,?_assertEqual({2019,12,31}, kz_date:previous_day({2020,01,01}))
,?_assertEqual({2020,02,29}, kz_date:previous_day({2020,03,01}))
,?_assertEqual({2019,02,28}, kz_date:previous_day({2019,03,01}))
].

pad_month_test_() ->
[?_assertEqual(<<"10">>, kz_date:pad_month(10))
,?_assertEqual(<<"10">>, kz_date:pad_month(<<"10">>))
Expand Down

0 comments on commit da74aa7

Please sign in to comment.