Archive

Archive for September, 2009

Date time manipulation howtos

September 6th, 2009

Erlang offers calendar module which provides computation of date, time and number of date time conversion functions. For more details, please refer to documentation for this module
Here are some examples:

Data types


Date = {Year, Month, Day}
Time = {Hour, Minute, Second}

where

Year = an integer and cannot be abbreviated. E.g.: 93 denotes year 93, not 1993
Month = 1..12
Day = 1..31
Hour = 0..23
Minute = 0..59
Second = 0..59

How to obtain local date time

{Date, Time} = calendar:local_time()

1> Current = calendar:local_time().
{{2009,9,7},{12,32,22}}
2> {{Current_Year, Current_Month, Current_Day}, _ } = Current.
{{2009,9,7},{12,32,22}}
3> Current_Year.
2009
4> Current_Month.
9
5> Current_Day.
7
6> { _, {Current_Hour, Current_Min, Current_Second}} = Current. 
{{2009,9,7},{12,32,22}}
7> Current_Hour.
12
8> Current_Min.
32
9> Current_Second.
22

How to obtain current UTC time

{Date, Time} = calendar:universal_time()

How to convert time to seconds since midnight and via versa

Seconds = calendar:time_to_seconds(Time)
Time = calendar:seconds_to_time(Seconds)

10> Time1 = {10, 6, 30}.
{10,6,30}
11> Seconds = calendar:time_to_seconds(Time1).
36390
12> calendar:seconds_to_time(Seconds).
{10,6,30}

How to verify if a year is leap year

Bool = calendar:is_leap_year(Year)

14> calendar:is_leap_year(2008).
true
15> calendar:is_leap_year(2009).
false

How to check if a date is valid

Bool = calendar:valid_date(Date)
Bool = calendar:valid_date(Year, Month, Day)

16> calendar:valid_date({2009,12,12}).
true
17> calendar:valid_date({2009,13,12}).
false
18> calendar:valid_date(2009, 12, 31).
true
19> calendar:valid_date(2008, 2, 29).
true

How to find out day of the week

DayNumber = calendar:day_of_the_week(Date)
DayNumber = calendar:day_of_the_week(Year, Month, Day)
1 = Monday, 2 = Tuesday, ….and 7 = Sunday

20> calendar:day_of_the_week({2009,9,7}).
1
21> calendar:day_of_the_week(2009, 9, 9).
3

How to find out last day of a month

LastDay = calendar:last_day_of_the_month(Year, Month)

22> calendar:last_day_of_the_month(2008, 2).   
29
23> calendar:last_day_of_the_month(2009, 8).
31

How to calculate date time difference

{Days, Time} = calendar:time_difference(DT1, DT2)
DT1 = {Date1, Time1}
DT2 = {Date2, Time2}
Logically equivalent to DT2 – DT1

7> Date1={{2009,8,30}, {23,0,0}}.
{{2009,8,30},{23,0,0}}
8> Date2={{2009,9,30}, {23,0,0}}.
{{2009,9,30},{23,0,0}}
9> calendar:time_difference(Date2, Date1).
{-31,{0,0,0}}
10> calendar:time_difference(Date1, Date2).
{31,{0,0,0}}
11> Date3={{2008,8,30},{23,0,0}}.
{{2008,8,30},{23,0,0}}
12> calendar:time_difference(Date1, Date3).
{-365,{0,0,0}}

Basic, DateTime , , , ,