Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-04-25
Convert Unix Timestamp to Datetime in Perl

How to convert Unix timestamp to Datetime in Perl

🎈 🎈 🎈
+1

    my $unix_timestamp = 1699336923;
    my ($sec, $min, $hour, $day, $month, $year) = localtime($unix_timestamp);
    
    # Adjust year and month to human-readable format
    $year += 1900;
    $month += 1;
    
    print "Converted Date: $year-$month-$day $hour:$min:$sec\n";
        

Output:
Converted Date: 2023-11-07 06:02:03
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this Perl example, the Unix timestamp 1699336923 is passed to the localtime() function, which returns a list containing the second, minute, hour, day, month (0-based), and year (since 1900). This is because, in Perl, years are returned as the number of years since 1900 (so you need to add 1900 to get the actual year) and months are 0-based (therefore January is 0), so you add 1 to get the actual month number.
These values are then adjusted to the proper year and month formats and printed as a human-readable date.
For the given Unix timestamp the output would be 2023-11-07 06:02:03.


Other useful Perl date functions

Function Description Example
time() Returns the current Unix timestamp (seconds since January 1, 1970). time() returns 1693227296
localtime() Returns the local date and time based on the Unix timestamp or the current time if no timestamp is provided. localtime(time()) returns Tue Aug 28 12:34:56 2024
gmtime() Returns the UTC date and time based on the Unix timestamp or the current time if no timestamp is provided. gmtime(time()) returns Tue Aug 28 12:34:56 2024
strftime() Formats a date and time according to the specified format using the POSIX module. strftime("%Y-%m-%d %H:%M:%S", localtime(time())) returns 2024-08-28 12:34:56
timelocal() Converts a local date and time to a Unix timestamp using the Time::Local module. timelocal(0, 34, 12, 28, 7, 2024) returns 1693227296
timegm() Converts a UTC date and time to a Unix timestamp using the Time::Local module. timegm(0, 34, 12, 28, 7, 2024) returns 1693227296
DateTime->now() Returns the current date and time as a DateTime object. DateTime->now() returns 2024-08-28T12:34:56
DateTime->from_epoch() Creates a DateTime object from a Unix timestamp. DateTime->from_epoch(epoch => 1693227296) returns 2024-08-28T12:34:56
DateTime->ymd() Formats a DateTime object as 'YYYY-MM-DD'. $dt->ymd() returns 2024-08-28
DateTime->strftime() Formats a DateTime object using a strftime-style format string. $dt->strftime("%Y-%m-%d %H:%M:%S") returns 2024-08-28 12:34:56
Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-04-25
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder