Search code examples
perlunixunix-timestamp

Perl time vs. Unix date output inconsistency


I am a total beginner in Perl and trying my first Perl script to convert time information in epoch-seconds to a specific format. I understand that month Jan = 0 and year 1900 = 0 in Perl from other Stack Overflow questions. Even after adjusting for them, I am not seeing identical outputs between Unix and Perl.

Here is what I tried and got.

Unix:

date -d @915149280

gives me:

Thu Dec 31 19:08:00 EST 1998

Perl:

$time = 915149280;
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = gmtime($time);
$year = $year + 1900;
$mon = $mon + 1;
print "Formated time = $mday/$mon/$year $hour:$min:$sec $weekday[$wday]\n";

gives me:

Formatted time = 1/1/1999 0:8:0 Fri

Is there a mistake in the Perl lines? What should I do to get the same output as the date command? (not the formatting part, but time).

I am not looking for all the fields. Only the year is important to me.


Solution

  • I assume you're talking about the time difference rather than the format difference, since your Perl code doesn't even attempt to replicate that format.

    Use localtime instead of gmtime. The date command uses your local time by default. Notice that it says "EST", but gmtime returns UTC, a 5 hour difference.

    You should also consider using a module to handle the date formatting. But that won't prevent confusion between local time and UTC.