[Munich-pm] This time on-topic: How to get Central European Time on any server anywhere in the world

Steffen Beyer steffenolfbeyer at yahoo.com.br
Mi Mär 30 10:19:20 PDT 2016


Dear Perl Mongers,
I just encountered the problem that I needed Central European Time (for timestamps etc.) on a server located in the USA.
Anybody can easily verify that the rules for daylight savings time are much less predictable in the USA than in Central Europe (last Sunday in March at 2:00 => DST, last Sunday in October at 3:00 => winter time).
There are times when the USA are in DST but not Central Europe, and vice-versa.
This could therefore be a real challenge to calculate.
However, we make two observations: firstly, every Un*x server knows GMT. Secondly, coincidentally the switch-over times in Europe for going to DST and back are always at GMT 1:00.
Now with Date::Calc to the rescue, we ask the server to give us GMT (and let him handle the idiosyncracies of the US-American DST rules) and calculate whether we are between the last Sunday in March at 1:00 GMT and the last Sunday in October at 1:00 GMT, and add 1 or 2 hours (for CET=GMT+1 or CEST=GMT+2, according to DST or not).
Voila!
The subroutine that does this is relatively simple:use Date::Calc qw(:all);sub Central_European_Time
{
    my(@Now)  = Gmtime();
    my($year) = $Now[0];
    my(@DST, at CET);
    @DST = Nth_Weekday_of_Month_Year($year, 3,7,4) unless (@DST = Nth_Weekday_of_Month_Year($year, 3,7,5));
    @CET = Nth_Weekday_of_Month_Year($year,10,7,4) unless (@CET = Nth_Weekday_of_Month_Year($year,10,7,5));
    my $now = (((Day_of_Year(@Now[0,1,2])-1) * 24 + $Now[3]) * 60 + $Now[4]) * 60 + $Now[5];
    my $dst =  ((Day_of_Year(@DST)       -1) * 24 + 1) * 3600;
    my $cet =  ((Day_of_Year(@CET)       -1) * 24 + 1) * 3600;
    if (($dst <= $now) and ($now < $cet)) { return(Add_Delta_YMDHMS(@Now[0,1,2,3,4,5],0,0,0,2,0,0)); }
    else                                  { return(Add_Delta_YMDHMS(@Now[0,1,2,3,4,5],0,0,0,1,0,0)); }
}It returns a list of the form ($year, $month,$day,$hour,$min,$sec).
See also http://sb.fluomedia.org/scripts/time_pl
I hope you like it! :-)
Cheers,Steffen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/munich-pm/attachments/20160330/1605a3b6/attachment.html>


Mehr Informationen über die Mailingliste Munich-pm