Erlang Central

# Difference between revisions of "Time Arithmetic"

From ErlangCentral Wiki

## Problem

You have a date and time and want to find the date and time of some period in the future or past.

## Solution

By using the functions counting Gregorian days or seconds, subtracting, and adding seconds is all you need:

```1> NowSecs = calendar:datetime_to_gregorian_seconds(
1>    calendar:universal_time()).
63260897707
2> Twenty_Four_Hours_From_Now = 24 * 60 * 60.
86400
3> NewTimeSecs = NowSecs + Twenty_Four_Hours_From_Now.'
63260984107
4> New_Date_Time = calendar:gregorian_seconds_to_datetime
4> (NewTimeSecs).
{{2004,8,29},{7,35,7}}
```

Important Note: If time values are given as local time, they must be converted to universal time. Otherwise, you will have a time skewed by the difference between the local time measurement and UTC.

Furthermore, if you use your understand of the problem at hand, you can easily add or subtract given time units directly (instead of handling all time in seconds). In this case, you can use any kind of time as input.

```5> {{Year,Month,Day}, {Hour,Min,Sec}} = erlang:localtime().
{{2004,8,28},{0,44,53}}
6> NewDay = Day + 2.
30
7> calendar:valid_date({Year,Month,NewDay}).
true
8> OtherNewDay = Day+15.
43
9> calendar:valid_date({Year,Month,OtherNewDay}).
false
```