DateTime-Format-Intl
view release on metacpan or search on metacpan
NAME
DateTime::Format::Intl - A Web Intl.DateTimeFormat Class Implementation
SYNOPSIS
use DateTime;
use DateTime::Format::Intl;
my $dt = DateTime->now;
my $fmt = DateTime::Format::Intl->new(
# You can use ja-JP (Unicode / web-style) or ja_JP (system-style), it does not matter.
'ja_JP', {
localeMatcher => 'best fit',
# The only one supported. You can use 'gregory' or 'gregorian' indifferently
calendar => 'gregorian',
# see getNumberingSystems() in Locale::Intl for the supported number systems
numberingSystem => 'latn',
formatMatcher => 'best fit',
dateStyle => 'long',
timeStyle => 'long',
},
) || die( DateTime::Format::Intl->error );
say $fmt->format( $dt );
my $fmt = DateTime::Format::Intl->new(
# You can also use ja-JP (Unicode / web-style) or ja_JP (system-style), it does not matter.
'ja_JP', {
localeMatcher => 'best fit',
# The only one supported
calendar => 'gregorian',
numberingSystem => 'latn',
hour12 => 0,
timeZone => 'Asia/Tokyo',
weekday => 'long',
era => 'short',
year => 'numeric',
month => '2-digit',
day => '2-digit',
dayPeriod => 'long',
hour => '2-digit',
minute => '2-digit',
second => '2-digit',
fractionalSecondDigits => 3,
timeZoneName => 'long',
formatMatcher => 'best fit',
},
) || die( DateTime::Format::Intl->error );
say $fmt->format( $dt );
In basic use without specifying a locale, "DateTime::Format::Intl" uses
the default locale and default options:
use DateTime;
my $date = DateTime->new(
year => 2012,
month => 11,
day => 20,
hour => 3,
minute => 0,
second => 0,
# Default
time_zone => 'UTC',
);
# toLocaleString without arguments depends on the implementation,
# the default locale, and the default time zone
say DateTime::Format::Intl->new->format( $date );
# "12/19/2012" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)
Using "timeStyle" and "dateStyle":
Possible values are: "full", "long", "medium" and "short"
my $now = DateTime->new(
year => 2024,
month => 9,
day => 13,
hour => 14,
minute => 12,
second => 10,
time_zone => 'Europe/Paris',
);
my $shortTime = DateTime::Format::Intl->new('en', {
timeStyle => 'short',
});
say $shortTime->format( $now ); # "2:12 PM"
my $shortDate = DateTime::Format::Intl->new('en', {
dateStyle => 'short',
});
say $shortDate->format( $now ); # "09/13/24"
It relies on DateTime::Format::Unicode, DateTime::Locale::FromCLDR,
Locale::Unicode::Data, which provides access to all the Unicode CLDR
(Common Locale Data Repository) <https://cldr.unicode.org/>, and
Locale::Intl to achieve similar results. It requires perl v5.10.1
minimum to run.
It is very elaborate and the algorithm provides the same result you
would get with a web browser. The algorithm itself is quite complex and
took me several months to implement, given all the dependencies with the
modules aforementioned it relies on, that I also had to build to make
the whole thing work.
I hope they will benefit you as they benefit me.
Because, just like its JavaScript equivalent, "DateTime::Format::Intl"
does quite a bit of look-ups and sensible guessing upon object
instantiation, you want to create an object for a specific format, cache
it and re-use it rather than creating a new one for each date
formatting.
"DateTime::Format::Intl" uses a set of culturally sensible default
values derived directly from the web browsers own default. Upon object
instantiation, it uses a culturally sensitive scoring to find the best
matching format pattern available in the Unicode CLDR (Common Locale
Data Repository) data for the options provided. It appends any missing
components
<https://www.unicode.org/reports/tr35/tr35-dates.html#Missing_Skeleton_F
ields>, if any. Finally, it adjusts the best pattern retained to match
perfectly the options of the user.
CONSTRUCTOR
new
This takes a "locale" (a.k.a. language "code" compliant with ISO 15924
<https://en.wikipedia.org/wiki/ISO_15924> as defined by IETF
<https://en.wikipedia.org/wiki/IETF_language_tag#Syntax_of_language_tags
>) and an hash or hash reference of options and will return a new
DateTime::Format::Intl object, or upon failure "undef" in scalar context
and an empty list in list context.
Each option can also be accessed or changed using their corresponding
method of the same name.
See the CLDR (Unicode Common Locale Data Repository) page
<https://cldr.unicode.org/translation/date-time/date-time-patterns> for
more on the format patterns used.
Supported options are:
Locale options
* "localeMatcher"
The locale matching algorithm to use. Possible values are "lookup"
and "best fit"; the default is "best fit". For information about
this option, see Locale identification and negotiation
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/G
lobal_Objects/Intl#locale_identification_and_negotiation>.
Whatever value you provide, does not actually have any influence on
the algorithm used. "best fit" will always be the one used.
* "calendar"
The calendar to use, such as "chinese", "gregorian" (or "gregory"),
"persian", and so on. For a list of calendar types, see
Intl.Locale.prototype.getCalendars()
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/G
lobal_Objects/Intl/Locale/getCalendars#supported_calendar_types>,
and the perl module Locale::Intl. This option can also be set
through the "ca" Unicode extension key; if both are provided, this
options property takes precedence. See "ca" in Locale::Unicode
For example, a Japanese locale with the "japanese" calendar
extension set:
my $fmt = DateTime::Format::Intl->new( 'ja-Kana-JP-u-ca-japanese' );
The only value calendar type supported by this module is
"gregorian". Any other value will return an error.
* "numberingSystem"
The numbering system to use for number formatting, such as
"fullwide", "hant", "mathsans", and so on. For a list of supported
numbering system types, see getNumberingSystems(). This option can
also be set through the nu Unicode extension key; if both are
provided, this options property takes precedence.
For example, a Japanese locale with the "jpanfin" number system
extension set and with the "jptyo" time zone:
my $fmt = DateTime::Format::Intl->new( 'ja-u-nu-jpanfin-tz-jptyo' );
See Mozilla documentation
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/G
lobal_Objects/Intl/Locale/getNumberingSystems>, and also the perl
module Locale::Intl
* "hour12"
Whether to use 12-hour time (as opposed to 24-hour time). Possible
values are "true" (1) and "false" (0); the default is locale
dependent. When "true", this option sets "hourCycle" to either "h11"
or "h12", depending on the locale. When "false", it sets hourCycle
to "h23". "hour12" overrides both the hc locale extension tag and
the "hourCycle" option, should either or both of those be present.
* "hourCycle"
The hour cycle to use. Possible values are "h11", "h12", "h23", and
"h24". This option can also be set through the "hc" Unicode
extension key; if both are provided, this options property takes
precedence.
See Mozilla documentation
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/G
lobal_Objects/Intl/DateTimeFormat/DateTimeFormat#hourcycle>
* "timeZone"
The time zone to use. Time zone names correspond to the Zone and
Link names of the IANA Time Zone Database
<https://www.iana.org/time-zones>, such as "UTC", "Asia/Tokyo",
"Asia/Kolkata", and "America/New_York". Additionally, time zones can
be given as UTC offsets in the format "±hh:mm", "±hhmm", or "±hh",
for example as "+01:00", -2359, or +23. The default is the runtime's
default time zone.
See Mozilla documentation
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/G
lobal_Objects/Intl/DateTimeFormat/DateTimeFormat#timezone>
Date-time component options
* "weekday"
The representation of the weekday. Possible values are:
* "long"
This would return an array containing the following hash references:
{ type => 'weekday', value => 'mercredi' },
{ type => 'literal', value => ' ' },
{ type => 'day', value => '10' },
{ type => 'literal', value => ' ' },
{ type => 'month', value => 'janvier' },
{ type => 'literal', value => ' Ã ' },
{ type => 'hour', value => '19' },
{ type => 'literal', value => ':' },
{ type => 'minute', value => '00' }
The "formatToParts()" method takes an optional DateTime object, and
returns an array of locale-specific tokens representing each part of the
formatted date produced by this DateTime::Format::Intl object. It is
useful for custom formatting of date strings.
If no DateTime object is provided, it will default to the current date
and time.
The properties of the hash references returned are as follows:
* "day"
The string used for the day, for example 17.
* "dayPeriod"
The string used for the day period, for example, "AM", "PM", "in the
morning", or "noon"
* "era"
The string used for the era, for example "BC" or "AD".
* "fractionalSecond"
The string used for the fractional seconds, for example 0 or 00 or
000.
* "hour"
The string used for the hour, for example 3 or 03.
* "literal"
The string used for separating date and time values, for example
"/", ",", "o'clock", "de", etc.
* "minute"
The string used for the minute, for example 00.
* "month"
The string used for the month, for example 12.
* "relatedYear"
The string used for the related 4-digit Gregorian year, in the event
that the calendar's representation would be a yearName instead of a
year, for example 2019.
* "second"
The string used for the second, for example 07 or 42.
* "timeZoneName"
The string used for the name of the time zone, for example "UTC".
Default is the timezone of the current environment.
* "weekday"
The string used for the weekday, for example "M", "Monday", or
"Montag".
* "year"
The string used for the year, for example 2012 or 96.
* "yearName"
The string used for the yearName in relevant contexts, for example
"geng-zi"
resolvedOptions
The "resolvedOptions()" method returns an hash reference with the
following properties reflecting the "locale" and date and time
formatting "options" computed during the object instantiation.
* "locale"
The BCP 47 language tag for the locale actually used. If any Unicode
extension values were requested in the input BCP 47 language tag
that led to this locale, the key-value pairs that were requested and
are supported for this locale are included in locale.
* "calendar"
E.g. "gregory"
* "numberingSystem"
The values requested using the Unicode extension keys "ca" and "nu"
or filled in as default values.
* "timeZone"
The value provided for this property in the options argument;
defaults to the runtime's default time zone. Should never be
undefined.
* "hour12"
The value provided for this property in the options argument or
filled in as a default.
* "weekday", "era", "year", "month", "day", "hour", "minute",
"second", "timeZoneName"
The values resulting from format matching between the corresponding
properties in the options argument and the available combinations
and representations for date-time formatting in the selected locale.
Some of these properties may not be present, indicating that the
corresponding components will not be represented in formatted
output.
OTHER NON-CORE METHODS
error
Sets or gets an exception object
When called with parameters, this will instantiate a new
DateTime::Format::Intl::Exception object, passing it all the parameters
received.
When called in accessor mode, this will return the latest exception
object set, if any.
fatal
$fmt->fatal(1); # Enable fatal exceptions
$fmt->fatal(0); # Disable fatal exceptions
my $bool = $fmt->fatal;
Sets or get the boolean value, whether to die upon exception, or not. If
set to true, then instead of setting an exception object, this module
will die with an exception object. You can catch the exception object
then after using "try". For example:
use v.5.34; # to be able to use try-catch blocks in perl
use experimental 'try';
no warnings 'experimental';
try
{
my $fmt = DateTime::Format::Intl->new( 'x', fatal => 1 );
}
catch( $e )
{
say "Error occurred: ", $e->message;
( run in 0.864 second using v1.01-cache-2.11-cpan-39bf76dae61 )