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

/ Erlang.TimeToEpoch

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 DMYHMS to Seconds

Problem

You want to convert a date, a time, or both with distinct values for day, month, year, etc. to seconds.

Solution

First, it is important to note that time (in Erlang) is always an integer based on a platform-specific starting date, an Epoch, (with a platform-specific minimum and maximum value). Keeping that into consideration, and using various Erlang built-in functions, we can get the number of seconds of a given date, and time. For instance, to get the seconds corresponding to the date, and time: "Wed Apr 21 13:01:01-0500 2004" you could simply:

1> LocalDateTime={{2004,04,21},{13,01,01}}.
{{2004,4,21},{13,1,1}}
2> calendar:datetime_to_gregorian_seconds(LocalDateTime).
63249771661

Discussion

All of Erlangs date functions are in compliance with the Gregorian calendar, with its Epoch at year 0. So, the seconds value may differ from what we would expect from most UNIX languages (which would record their Epoch as January 1, 1970). So these languages would report a value of 1082570461, rather than 63249771661.

To prove this, let's get the gregorian seconds for 12:00:00 AM on January 1, 1970:

3> UnixEpoch={{1970,1,1},{0,0,0}}.
{{1970,1,1},{0,0,1}}
4> calendar:datetime_to_gregorian_seconds(UnixEpoch).
62167219200
5> 63249771661 - 62167219200.
1082552461
QED

Comments here

Based on work by FranciscoSolsona.

-- BrentAFulgham - 28 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: TimeRecipes
TopicOrder: 020

 
 
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