in reply to Getting seconds from date

Have you tried converting the date string you get into the format that localtime returns? It's not really hard, you just have to remember that the localtime API is broken and counts months from 0.

Replies are listed 'Best First'.
Re^2: Getting seconds from date
by Marshall (Canon) on Jun 06, 2011 at 07:59 UTC
    I think "broken" is too harsh a word. I see why this was done, so that this number can be used an index into an array of text translation values. A lot of stuff in the C library is truly ancient and predates C. Nowadays, I would imagine that location "0" would just get "burned" and not used so that the indicies have the normal human meaning. But an ancient decision made another choice.
    my @monthText = qw (jan feb mar apr may jun jul aug sep oct nov dec); print "$monthText[0] is for January\n"; print "$monthText[11] is for December\n";
Re^2: Getting seconds from date
by ultranerds (Hermit) on Jun 05, 2011 at 10:21 UTC
    Hi,

    Thanks for the reply. I tried converting it to the localtime format, but unfortunatly didn't have much success. Do you have a module in mind to do that?

    TIA

    Andy

      Dealing with dates and times is quite tricky. Have a look at the module suggestions given in the QandASection: dates and times section, e.g. Fast(er) date parsing.

      However, if you insist on using Time::Local, you can use this snippet to get started...

      use strict; use warnings; use Time::Local qw(timelocal); sub localdate2epoch { my $date = shift; # insert some sanity checks and normalisation (whitespace removal, e +tc.) my ($year, $mon, $mday, $hour, $min, $sec) = split /[-\s:]+/, $date +; # insert more sanity checks # .oO( get the impression here, it's better to use a module ;-) $year -= 1900; # correct year (2011 = 1900 + 111); $mon -= 1; # correct month (0..11) return timelocal( $sec, $min, $hour, $mday, $mon, $year ); } my $date = "2011-06-05 11:00:00"; my $now_in_secs = localdate2epoch $date; print "In : $date\n"; print "epo: $now_in_secs\n"; print "Out: ", scalar localtime $now_in_secs, "\n"; __END__ In : 2011-06-05 11:00:00 epo: 1307264400 Out: Sun Jun 5 11:00:00 2011

        You legend, works a charm :)

        Thanks!

        Andy