How do I add seconds, minutes, or hours to a DateTime structure in Erlang?

Full article

Some languages, like Ruby, give you 12 ways to do the same thing. Other languages, like Erlang, make it tough to find 1 way to do something. Awhile back, I was trying to add a period of time to an existing DateTime value (in {{Y,M,D},{H,m,s}} format), but I couldn't find a function (such as in the Calendar module) that allowed me to manipulate a DateTime value directly. Basically, my question was...

How do I add xx seconds to a DateTime value?

Use the Calendar module to convert the DateTime to seconds, which makes it easier to add the desired seconds, minutes, hours, etc.

For example, to add 10 seconds:

Date = {{2018,8,14},{13,10,25}}.
DateInSec = calendar:datetime_to_gregorian_seconds(Date).  % 63701471425
NewDateInSec = DateInSec + 10.                             % 63701471435
calendar:gregorian_seconds_to_datetime(NewDateInSec).      % {{2018,8,14},{13,10,35}}

For 10 minutes or 10 hours, just perform a little math:

Date = {{2018,8,14},{13,10,25}}.
DateInSec = calendar:datetime_to_gregorian_seconds(Date).  % 63701471425
NewDateInSec = DateInSec + (10 * 60 * 60).                 % 63701507425 (10 hours)
calendar:gregorian_seconds_to_datetime(NewDateInSec).      % {{2018,8,14},{23,10,25}}

To make life easier, I ended up creating a function to add additional time to (or subtract time from) an existing DateTime:

-type datetime() :: {{non_neg_integer(), pos_integer(), pos_integer()},
                     {non_neg_integer(), non_neg_integer(), non_neg_integer()}}.
-type timespan() :: {integer(), integer(), integer()}.

-spec add_time_to_datetime(datetime(), timespan()) -> datetime().
add_time_to_datetime(Date, {Hour, Min, Sec}) ->
    DateInSeconds = calendar:datetime_to_gregorian_seconds(Date),
    NewDateInSeconds = DateInSeconds + (Hour * 60 * 60) + (Min * 60) + Sec,


Grant Winney

I write when I've got something to share - a personal project, a solution to a difficult problem, or just an idea. We learn by doing and sharing. We've all got something to contribute.

Comments / Reactions

One of the most enjoyable things about blogging is engaging with and learning from others. Leave a comment below with your questions, comments, or ideas. Let's start a conversation!