Wednesday, April 13, 2011

How to Generate a YYYY-MM-DD Datestamp in Perl

use strict;
use warnings;

# Extract the year, month, and day from the built-in localtime function.
# Note: 
# - (localtime)[5] returns years since 1900, so we add 1900 to get the full year.
# - (localtime)[4] returns the month from 0-11, so we add 1 for standard formatting.
# - (localtime)[3] returns the day of the month.

my $datestamp = sprintf(
    "%04d-%02d-%02d", 
    (localtime)[5] + 1900, 
    (localtime)[4] + 1, 
    (localtime)[3]
);

# Print the formatted YYYY-MM-DD datestamp
print "$datestamp\n";

No comments: