e r l a n g : c o o k b o o k

/ Erlang.TimeArithmetic

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Time Arithmetic

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}}

Discussion

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

See Also

Inspiration for useful time functions can be obtained by looking at SRFI 19: Time Data Types and Procedures

Comments here

Based on work by FranciscoSolsona.

-- BrentAFulgham - 28 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: TimeRecipes
TopicOrder: 040

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest