Search code examples
perldatetimedatetime-format

Limit DateTime strftime precision to milliseconds


I'm working on a project which involves integrating with a 3rd party API. As part of the contract, I need to include a UTC date string in the below ISO format, within the XML body of the HTTP request:

yyyy-MM-ddTHH:mm:ss.sssZ

I've been trying a few options in re.pl to generate a date string in the above format. So far, I've been able to come up with this:

use DateTime;

my $now_utc = DateTime->now(time_zone => 'UTC');

my $now_iso_format = $now_utc->strftime('%Y-%m-%dT%H:%M:%S.%sZ');

When I execute these lines in re.pl, I get the date string in the format:

2022-02-07T03:55:22.1644206122Z

How do I limit the precision to milliseconds? As you can see, right now it's nanoseconds.


Solution

  • Details are listed on strftime patterns page and %N is for fractional seconds digits

    .. -> strftime('%Y-%m-%dT%H:%M:%S.%3NZ');