$self->_message( 4, "Default number system for locale '${locale}' is: ", sub{ dump( $ns_default) }, ", and has the following definition: ", sub{ dump( $ns_default_def) } );
$self->_message( 4, "Locale 'nu' extension value '${num_sys}' looks valid.");
}
else
{
warn( "Warning only: unsupported numbering system provided (${locale_num_sys}) via the locale \"nu\" extension (${locale}).") if( warnings::enabled() );
}
}
# If no number system was provided, or if it was maybe invalid, we check the locale's default number system, and before that we make sure to expand the locale if necessary so that, for example, 'en' becomes 'en-Latn-US', or 'ar' becomes 'ar-Arab-EG'
# If the locale already has a country code / region associated, it is specific enough
$self->_message( 4, "Country code for locale '${locale}' does not exist, using likely locale to get the country code, and get a more specific locale for the numbering system.");
return( $self->error( "Unable to find any numbering system for any locale in the inheritance tree @$expanded_locale_tree") ) if( !defined( $locale_ns_def) );
$self->_message( 4, "The expanded locale '${expanded_locale}' has the following numbering system, checking each possible value: ", sub{ dump( $locale_ns_def) } );
foreachmy$ns_type( qw( number_system native traditional finance ))
{
# It may not be defined for that locale, and in this case, we skip to the next one.
# It needs to be 'numeric', as opposed to 'algorithmic', or else we cannot use it
if( $ns_def->{type} eq 'numeric'&&
defined( $ns_def->{digits} ) &&
ref( $ns_def->{digits} ) eq 'ARRAY'&&
scalar( @{$ns_def->{digits}} ) )
{
$self->_message( 4, "Found a match for the numbering system '", $locale_ns_def->{ $ns_type}, "'");
$ns_digits= $ns_def->{digits};
$num_sys= $locale_ns_def->{ $ns_type};
lastLOCALE;
}
}
}
}
}
# Still have not found anything
if( !length( $num_sys// '') )
{
$self->_message( 4, "No numbering system found so far, falling back on the locale's preferred one '", ( ( $systems->{number_system} || $systems->{native} || $systems->{traditional} ) // 'undef'), "' or 'latn' in last resort.");
$self->_message( 4, "Trying to get the time relative pattern for count '${cnt}', field_type '${unit}', field_length '${this_style}', relative '${cldr_num}'");
# NOTE: CBOR will call the THAW method with the stored classname as first argument, the constant string CBOR as second argument, and all values returned by FREEZE as remaining arguments.
# NOTE: Storable calls it with a blessed object it created followed with $cloning and any other arguments initially provided by STORABLE_freeze
You can also pass one or two L<DateTime> objects, and let this interface find out the greatest difference between the two objects. If you pass only one L<DateTime> object, this will instantiate another L<DateTime> object, using the method L<now|DateTime/now> with the C<time_zone> value from the first object.
my $dt = DateTime->new(
year => 2024,
month => 8,
day => 15,
);
$fmt->format( $dt );
# Assuming today is 2024-12-31, this would return: "1 qtr. ago"
or, with 2 L<DateTime> objects:
my $dt = DateTime->new(
year => 2024,
month => 8,
day => 15,
);
my $dt2 = DateTime->new(
year => 2022,
month => 2,
day => 22,
);
$fmt->format( $dt => $dt2 ); # "2 yr. ago"
Using the auto option
If C<numeric> option is set to C<auto>, it will produce the string C<yesterday> or C<tomorrow> instead of C<1 day ago> or C<in 1 day>. This allows to not always have to use numeric values in the output.
# Create a relative time formatter in your locale with numeric option set to 'auto'.
my $fmt = DateTime::Format::RelativeTime->new( 'en', { numeric => 'auto' });
# Format relative time using negative value (-1).
$fmt->format( -1, 'day' ); # "yesterday"
# Format relative time using positive day unit (1).
$fmt->format( 1, 'day' ); # "tomorrow"
In basic use without specifying a locale, C<DateTime::Format::RelativeTime> uses the default locale and default options.
A word about precision:
When formatting numbers for display, this module uses up to 15 significant digits. This decision balances between providing high precision for calculations and maintaining readability for the user. If numbers with more than 15 significant digits are provided, they will be formatted to this limit, which should suffice for most practical applications:
my $num = 0.123456789123456789;
my $formatted = sprintf("%.15g", $num);
# $formatted would be "0.123456789123457"
For users requiring exact decimal representation beyond this precision, consider using modules like L<Math::BigFloat>.
It relies on L<Locale::Unicode::Data>, which provides access to all the L<Unicode CLDR (Common Locale Data Repository)|https://cldr.unicode.org/>, and L<Locale::Intl> to achieve similar results. It requires perl v5.10.1 minimum to run.
The algorithm provides the same result you would get with a web browser.
Because, just like its JavaScript equivalent, C<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.
=head1 CONSTRUCTOR
=head2 new
# Create a relative time formatter in your locale
# with default values explicitly passed in.
my $fmt = DateTime::Format::RelativeTime->new( 'en', {
localeMatcher => 'best fit', # other values: 'lookup'
numeric => 'always', # other values: 'auto'
style => 'long', # other values: 'short' or 'narrow'
Whatever value you provide, does not actually have any influence on the algorithm used. C<best fit> will always be the one used.
=item * C<numberingSystem>
The numbering system to use for number formatting, such as C<fullwide>, C<hant>, C<mathsans>, and so on. For a list of supported numbering system types, see L<getNumberingSystems()|Locale::Intl/getNumberingSystems>. This option can also be set through the L<nu|Locale::Unicode/nu> Unicode extension key; if both are provided, this options property takes precedence.
For example, a Japanese locale with the C<latn> number system extension set and with the C<jptyo> time zone:
my $fmt = DateTime::Format::RelativeTime->new( 'ja-u-nu-latn-tz-jptyo' );
However, note that you can only provide a number system that is supported by the C<locale>, and that is of type C<numeric>, i.e. not C<algorithmic>. For instance, you cannot specify a C<locale> C<ar-SA> (arab as spoken in Saudi Arabia) with a number system of Japan:
say $fmt->resolvedOptions->{numberingSystem}; # arab
It would reject it, and issue a warning, if warnings are enabled, and fallback to the C<locale>'s default number system, which is, in this case, C<arab>
Additionally, even though the number system C<jpanfin> is supported by the locale C<ja>, it would not be acceptable, because it is not suitable for datetime formatting since it is not of type C<numeric>, or at least this is how it is treated by web browsers (see L<here the web browser engine implementation|https://github.com/v8/v8/blob/main/src/objects/intl-objects.cc> and L<here for the Unicode ICU implementation|https://github.com/unicode-org/icu/blob/main/icu4c/source/i18n/numsys.cpp>). This API could easily make it acceptable, but it was designed to closely mimic the web browser implementation of the JavaScript API C<Intl.DateTimeFormat>. Thus:
my $fmt = DateTime::Format::RelativeTime->new( 'ja-u-nu-jpanfin-tz-jptyo' );
say $fmt->resolvedOptions->{numberingSystem}; # latn
The style of the formatted relative time. Possible values are:
=over 8
=item * C<long>
This is the default. For example: C<in 1 month>
=item * C<short>
For example: C<in 1 mo.>
=item * C<narrow>
For example: C<in 1 mo.>. The C<narrow> style could be similar to the C<short> style for some locales.
=back
=item * C<numeric>
Whether to use numeric values in the output. Possible values are C<always> and C<auto>; the default is C<always>. When set to C<auto>, the output may use more idiomatic phrasing such as C<yesterday> instead of C<1 day ago>.
=back
=head1 METHODS
=head2 format
my $fmt = new DateTime::Format::RelativeTime( 'en', { style => 'short' });
say $fmt->format( 3, 'quarter' );
# Expected output: "in 3 qtrs."
say $fmt->format( -1, 'day' );
# Expected output: "1 day ago"
say $fmt->format( 10, 'seconds' );
# Expected output: "in 10 sec."
Alternatively, you can pass two L<DateTime> objects, and C<format> will calculate the greatest time difference between the two. If you provide only one L<DateTime>, C<format> will instantiate a new L<DateTime> object using the C<time_zone> value from the first L<DateTime> object.
my $dt = DateTime->new(
year => 2024,
month => 8,
day => 15,
);
$fmt->format( $dt );
# Assuming today is 2024-12-31, this would return: "1 qtr. ago"
or, with 2 L<DateTime> objects:
my $dt = DateTime->new(
year => 2024,
month => 8,
day => 15,
);
my $dt2 = DateTime->new(
year => 2022,
month => 2,
day => 22,
);
$fmt->format( $dt => $dt2 ); # "2 yr. ago"
The C<format()> method of C<DateTime::Format::RelativeTime> instances formats a value and unit according to the C<locale> and formatting C<options> of this C<DateTime::Format::RelativeTime> object.
It returns a string representing the given value and unit formatted according to the locale and formatting options of this C<DateTime::Format::RelativeTime> object.
Supported parameters are:
=over 4
=item C<value>
Numeric value to use in the internationalized relative time message.
If the value is negative, the result will be formatted in the past.
=item C<unit>
Unit to use in the relative time internationalized message.
B<Note>: Most of the time, the formatting returned by C<format()> is consistent. However, the output may vary between implementations, even within the same C<locale> — output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should I<not> compare the results of C<format()> to hardcoded constants.
=head2 formatToParts
my $fmt = new DateTime::Format::RelativeTime( 'en', { numeric => 'auto' });
my $parts = $fmt->formatToParts( 10, 'seconds' );
say $parts->[0]->{value};
# Expected output: "in "
say $parts->[1]->{value};
# Expected output: "10"
say $parts->[2]->{value};
# Expected output: " seconds"
my $fmt = new DateTime::Format::RelativeTime( 'en', { numeric => 'auto' });
# Format relative time using the day unit
$fmt->formatToParts( -1, 'day' );
# [{ type: 'literal', value: 'yesterday' }]
$fmt->formatToParts( 100, 'day' );
# [
# { type => 'literal', value => 'in ' },
# { type => 'integer', value => 100, unit => 'day' },
# { type => 'literal', value => ' days' }
# ]
Just like for L<format|/format>, you can alternatively provide one or two L<DateTime> objects.
The C<formatToParts()> method of C<DateTime::Format::RelativeTime> instances returns an array reference of hash reference representing the relative time format in parts that can be used for custom locale-aware formatting.
The C<DateTime::Format::RelativeTime->formatToParts> method is a version of the L<format|/format> method that returns an array reference of hash reference which represents C<parts> of the object, separating the formatted number into its constituent parts and separating it from other surrounding text. These hash reference have two or three properties:
=over 4
=item * C<type> a string
=item * C<value>, a string representing the component of the output.
=item * C<unit>
The unit value for the number value, when the type is C<integer>
=back
Supported parameters are:
=over 4
=item * C<value>
Numeric value to use in the internationalized relative time message.
If the value is negative, the result will be formatted in the past.
=item * C<unit>
Unit to use in the relative time internationalized message.
my $fmt = new DateTime::Format::RelativeTime('en', { style => 'narrow' });
my $options1 = $fmt->resolvedOptions();
my $fmt2 = new DateTime::Format::RelativeTime('es', { numeric => 'auto' });
my $options2 = $fmt2->resolvedOptions();
say "$options1->{locale}, $options1->{style}, $options1->{numeric}";
# Expected output: "en, narrow, always"
say "$options2->{locale}, $options2->{style}, $options2->{numeric}";
# Expected output: "es, long, auto"
The C<resolvedOptions()> method of C<DateTime::Format::RelativeTime> instances returns a new hash reference with properties reflecting the options computed during initialisation of this C<DateTime::Format::RelativeTime> object.
For the details of the properties retured, see the L<new|/new> instantiation method.
=head1 CLASS METHODS
=head2 supportedLocalesOf
my $locales1 = ['ban', 'id-u-co-pinyin', 'de-ID'];
my $options1 = { localeMatcher: 'lookup' };
say DateTime::Format::RelativeTime->supportedLocalesOf( $locales1, $options1 );
# Expected output: ['id-u-co-pinyin', 'de-ID']
The C<DateTime::Format::RelativeTime->supportedLocalesOf> class method returns an array containing those of the provided locales that are supported in relative time formatting without having to fall back to the runtime's default locale.
Supported parameters are:
=over 4
=item * C<locale>
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the C<locales> argument, see the parameter description on the L<Locale::Intl> documentation.
=item * C<options>
An hash reference that may have the following property:
=over 8
=item * C<localeMatcher>
The locale matching algorithm to use. Possible values are C<lookup> and C<best fit>; the default is C<best fit>. For information about this option, see the L<DateTime::Format::Intl> documentation.
In reality, it does not matter what value you set, because this module only support the C<best fit> option.
=back
=back
=head1 OTHER NON-CORE METHODS
=head2 error
Sets or gets an L<exception object|DateTime::Format::Intl::Exception>
When called with parameters, this will instantiate a new L<DateTime::Format::Intl::Exception> object, passing it all the parameters received.
When called in accessor mode, this will return the latest L<exception object|DateTime::Format::Intl::Exception> set, if any.
=head2 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 L<exception object|DateTime::Format::Intl::Exception>, this module will die with an L<exception object|DateTime::Format::Intl::Exception>. You can catch the exception object then after using C<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;
# Error occurred: Invalid locale value "x" provided.
}
=for Pod::Coverage pass_error
=head1 AUTHOR
Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
=head1 SEE ALSO
L<perl>
=head1 COPYRIGHT & LICENSE
Copyright(c) 2024-2025 DEGUEST Pte. Ltd.
All rights reserved
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
=cut
Keyboard Shortcuts
Global
s
Focus search bar
?
Bring up this help dialog
GitHub
gp
Go to pull requests
gi
go to github issues (only if github is preferred repository)