|
Converting Date to Epoch -and- Epoch to Date
By: Bruce Bahlmann - Contributing Author (your
feedback
is important to us!)
In rails development, you may want to work with date in a more convenient
form than a date object or date string, such as Epoch which is also called Unix time,
or Unix timestamp which
represents the number of seconds that have elapsed since January 1, 1970.
Rails provides Time methods for working with epoch only actually implementing
these can evade or frustrate even the more experienced rails developer. So,
here are some proven ways of converting date to Epoch:
[Date to Epoch]
aa = '09/29/2011'
ab = aa.split(/\//) #=> ["09","29","2011"]
ac = Time.mktime(da[2],da[0],da[1]).tv_sec #=> 1317272400
bb = Time.parse(aa).to_i #=> 1317272400
Converting Epoch back to date is fairly simple.
[Epoch to Date]
ba = 1317272400
cb = Time.at(ba).strftime("%m/%d/%Y") #=> "09/29/2011"
Once you have a date string, you can now form a ruby date object as
follows:
[Date to Ruby Date Object]
rdo = DateTime.strptime("09/29/2011", "%m/%d/%Y").to_date #=> Thu, 29 Nov 2011
Having date in Epoch provides
a convenient way to work with date information that will work across diverse
systems. Note that a known limitation of Epoch is that it has a cutoff date
which will happen in the year 2038 (similar to the year 2000 bug - people
refer to this as the year 2038 bug). This represents the year that the values of
Epoch will exceed the size of the variable that holds them.
If your application has potential staying power beyond 2038, perhaps a better
alternative to Epoch is is to use Julian Date. Julian dates function similar
to Epoch but without any future date that cannot be supported.
Can Birds-Eye.Net help you or your Company?
Receive your Birds-Eye.Net articles and white
papers hot off
the presses by adding our RSS feed to your reader.
|
|
|
(C) Copyright Birds-Eye.Net, All rights reserved.
It is against the law to reproduce this content or any portion of it in any form without the explicit written permission of Birds-Eye Network Services, LLC. Federal copyright law (17 USC 504) makes it illegal, punishable with fines up to $100,000 per violation plus attorney's fees.
|