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

/ Erlang.TimeEpochToTime

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

Converting Epoch Seconds to DMYHMS

Problem

You have a date and time in Erlang Epoch seconds (i.e., Gregorian calendar year 0 seconds), and you want to calculate the individual DMYHMS values from it.

Solution

In recipe TimeToday we did exactly this but only for the current date. How about if we wanted to get the date, and time (DMYHMS) associated to a particular number of seconds? Once more we would use gre.

1> Seconds = 1083022458.
1083022458
2> DateTime = calendar:gregorian_seconds_to_datetime(Seconds).
{{34,4,26},{23,34,18}}
3> {{Year, Month, Day}, {Hour, Min, Sec}} = DateTime.
{{34,4,26},{23,34,18}}
4> io:fwrite("Today's Date is ~2B/~2B/~4B ~2B:~2.10.0B:~2.10.0B\n",
4> [Month, Day, Year, Hour, Min, Sec]).
Today's Date is  4/26/  34 23:34:18
ok                       

Discussion

In recipe TimeToday we discussed how to convert a date structure to a string. Convert in the opposite direction is also possible, and useful. Unfortunately, there is not a lot of build-in Erlang plumbing to do so. However, if we are very sure of the format we can easily extract the data we need using Erlang's ever-helpful io and io_lib modules:

5> Some_Date_String = "2004-04-26T18:26:18-0500".
"2004-04-26T18:26:18-0500".
6> {ok, [YYY,MMM,DD,HH,MM,SS,ZZ],_} = 
6> io_lib:fread("~4d-~2d-~2dT~2d:~2d:~2d-~4d", Some_Date_String).
{ok,[2004,4,26,18,26,18,500],[]}

Comments here

Based on work by FranciscoSolsona.

-- BrentAFulgham - 28 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: TimeRecipes
TopicOrder: 030

 
 
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