Home > Blockchain >  Force Time::Piece strftime to use a specific locale
Force Time::Piece strftime to use a specific locale

Time:10-02

How can Time::Piece->strftime be forced to output weeks' and months' names according to a specific locale, and not according to the current locale?

Setting $ENV{LC_ALL} to a specific locale (say, C.UTF-8) does not seem to work.

The following test script

#!/usr/bin/env perl

$ENV{LC_ALL} = "C.UTF-8";

use strict;
use warnings;
use Time::Piece;

my $s1 = "Mon, 26 Sep 2022";
my $format = "%a, %d %b %Y";
my $d = Time::Piece->strptime($s1, $format);
my $s2 = $d->strftime($format);

if ($s1 eq $s2) {
        print("OK: '$s1' == '$s2'\n");
} else {
        die("ERROR: '$s1' != '$s2'\n");
}

fails when run in, for example, a fr_CH.UTF-8 environment:

$ LC_ALL=fr_CH.UTF-8 ./test-strftime.pl
ERROR: 'Mon, 26 Sep 2022' != 'lun, 26 sep 2022'

CodePudding user response:

Perl relies on glibc to expand these formats, and it only initialises the locale definitions during startup. You can force re-initialization during runtime with POSIX::setlocale() to a locale of your choosing, but beware this is a truly global action and prior to Perl 5.28 it may even impact other threads.

Example (instead of $ENV{LC_ALL} = "C.UTF-8"):

use POSIX qw(locale_h);
setlocale(LC_ALL, "C.UTF-8");
  • Related