Time Arithmetic
From Erlang Community
(Difference between revisions)
| Revision as of 02:05, 26 August 2006 (edit) Cyberlync (Talk | contribs) ← Previous diff |
Current revision (01:12, 10 March 2007) (edit) (undo) Bfulgham (Talk | contribs) (→Solution) |
||
| (One intermediate revision not shown.) | |||
| Line 19: | Line 19: | ||
| </code> | </code> | ||
| - | 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. | + | '''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. | 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. | ||
| Line 35: | Line 35: | ||
| </code> | </code> | ||
| - | [[Category:CookBook]] | + | [[Category:CookBook]][[Category:DateTimeRecipes]] |
Current revision
[edit] Problem
You have a date and time and want to find the date and time of some period in the future or past.
[edit] 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
|

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

