Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Time, date conversion Error

Tags:

date

format

perl

This is a perl script for sql data pulling each day for 100 days starting from Oct 1 and SQL is quite picky in date formats(yyyy-mm-dd), so I've written the script as follows. However, at a specific day, on 2011-11-06, the time to date conversion is incorrect, and start and end date become the same.

$srt_date='2011-11-06'
$end_date='2011-11-06'

I don't know if this is perl error or something else.

use DBI;
use DBD::Oracle qw(:ora_types);
use Compress::Zlib;
use FileHandle;
use Date::Parse;
use Date::Format;

$st_day=str2time('2011-10-1');

@days=(0..100);

foreach $daynum (@days){
$dt1 = $st_day+3600*(24*$daynum);
$dt2 = $st_day+3600*(24*($daynum+1));
$srt_date = time2str("%d-%h-%Y", $dt1);
$end_date = time2str("%d-%h-%Y", $dt2);
print $srt_date, ',' ,$end_date, '\n';
my $sqlGetEid = "select x,y from z where DATETIME>='$srt_date' and DATETIME<'$end_date'";
}
like image 785
notilas Avatar asked Jan 22 '26 02:01

notilas


1 Answers

Here's how DateTime handles the DST transitions correctly:

use strict; #ALWAYS!
use warnings; #ALWAYS!
use DateTime;

my $st_day = '2011-10-1';

my ($year, $month, $day) = split /-/, $st_day;

my $dt = DateTime->new(
    year => $year,
    month => $month,
    day => $day,
    time_zone => 'local',
);

my @days = 0..100;
foreach my $daynum (@days) {
    my $dt1 = $dt->ymd;
    my $dt2 = $dt->add(days => 1)->ymd;
    printf "%s,%s\n", $dt1, $dt2;
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!