Entries Tagged 'Epoch'

Getting Midnight in the UNIX Epoch from Perl

By Timothy R Butler | Posted at 4:49 PM

Many computer functions dealing with time are calculated in the number of seconds since the UNIX Epoch. I wanted to get midnight tomorrow in those Epoch seconds so that my Bible word Wordle clone Biblicle could say when the next word would be available. I couldn’t easily do the entire calculation on the client side in JavaScript, because when the next word is served varies: if the user is logged in, it is at midnight for the user’s specified time zone on FaithTree (which may or may not match their computer’s time zone), but if the user is not logged in, it will be at midnight Central Time (“US/Chicago”).

The calculation needed to be done on the backend on the server, which is written in Perl. This page had a suggestion how to get the number of seconds so far elapsed in the day, which could easily be modified to instead give me the number of seconds remaining. Problem: I want to calculate on the basis of the local time zone not UTC/GMT. Thankfully, using Perl’s DateTime object, that isn’t difficult:

use DateTime;
my $tomorrow = DateTime->now(time_zone => $timeZone);
my $secs = ((23 - $tomorrow->hour) * 3600) + ((59 - $tomorrow->min) * 60) + (59 - $tomorrow->sec);
$tomorrow->add( seconds => ($secs + 1) );
my $tomorrowStarts = $tomorrow->epoch;

With that little code snippet, $tomorrowStarts will return the first second of tomorrow located to $timeZone and relative to the Epoch.