cpan beginner

How to format dates with DateTime in Perl?

Question

How to format dates with DateTime in Perl?

The DateTime module in Perl provides a powerful and flexible way to work with dates and times. One common task is formatting dates into readable strings. While DateTime objects store date and time components internally, you often want to display them in a particular format such as YYYY-MM-DD or DD/MM/YYYY.

Formatting Dates with DateTime

The DateTime class does not itself provide a direct format method, but it integrates seamlessly with the DateTime::Format::Strptime module (a core CPAN module) to format dates with custom patterns based on strftime-style sequences. Alternatively, you can use the strftime method from DateTime starting in Perl 5.10+ (with DateTime 0.52+) which provides a straightforward way.

Key points to know when formatting dates in Perl with DateTime:

  • strftime patterns: Use placeholders like %Y for 4-digit year, %m for month (01-12), %d for day, %H for hour, etc.
  • Locale awareness: Formatting honors locale for textual month/day names when using tokens like %B (full month name).
  • Time zone consistency: Ensure your DateTime objects are in the correct time zone before formatting them.
  • TMTOWTDI: Perl encourages flexibility, so you can use either DateTime::Format::Strptime or strftime depending on your needs.

Runnable Example Using DateTime and strftime

use strict;
use warnings;
use DateTime;

# Create a DateTime object for the current time
my $dt = DateTime->now(time_zone => 'local');

# Format date using strftime method (available in DateTime)
my $formatted1 = $dt->strftime("%Y-%m-%d %H:%M:%S");

# Alternative format showing textual month and day
my $formatted2 = $dt->strftime("%A, %B %d, %Y");

print "Formatted date/time (ISO-style): $formatted1\n";
print "Formatted date/time (Verbose): $formatted2\n";

Output might look like:


Formatted date/time (ISO-style): 2024-06-15 14:55:30
Formatted date/time (Verbose): Saturday, June 15, 2024

Using DateTime::Format::Strptime for Custom Parsing and Formatting

For more elaborate formatting or parsing, use DateTime::Format::Strptime which accepts the same strftime patterns and allows bidirectional conversions:

use strict;
use warnings;
use DateTime;
use DateTime::Format::Strptime;

my $dt = DateTime->now;

my $formatter = DateTime::Format::Strptime->new(
    pattern => '%d/%m/%Y %H:%M:%S',
);

my $formatted = $formatter->format($dt);

print "Formatted with DateTime::Format::Strptime: $formatted\n";

Common Pitfalls

  • Forgetting to use the right module or version: Make sure DateTime and optionally DateTime::Format::Strptime are installed. Both are widely available from CPAN.
  • Confusing format tokens: Perl’s format specifiers follow strftime conventions — for example, %m is numeric month, %M is minutes.
  • Time zone mix-ups: DateTime objects come with time zone info; formatting respects that, but you can normalize with $dt->set_time_zone('UTC') if necessary.
  • Context and sigils: Remember that $dt->strftime() returns a scalar string, so it must go into a scalar variable or print directly.

In summary, to format dates with DateTime, use the built-in strftime method for common and simple formatting. For more complex or locale-aware formatting, combine with DateTime::Format::Strptime. This flexibility is a great example of Perl’s TMTOWTDI (“There’s more than one way to do it”) philosophy, allowing you to pick the best approach for your use case.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 200ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Formatted date/time (ISO-style): 2025-12-30 12:45:24
Formatted date/time (Verbose): Tuesday, December 30, 2025
STDERR
(empty)

Was this helpful?

Related Questions