DateTime-Format-Intl

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN

# 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"
    

README.md  view on Meta::CPAN

    }
    catch( $e )
    {
        say "Oops: ", $e->message;
    }

Or, you could set the global variable `$FATAL_EXCEPTIONS` instead:

    use v5.34;
    use experimental 'try';
    no warnings 'experimental';
    local $DateTime::Format::Intl::FATAL_EXCEPTIONS = 1;
    try
    {
        my $fmt = DateTime::Format::Intl->new( 'x' );
        # More code
    }
    catch( $e )
    {
        say "Oops: ", $e->message;
    }

# VERSION

    v0.1.0

# DESCRIPTION

This module provides the equivalent of the JavaScript implementation of [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat)

It relies on [DateTime::Format::Unicode](https://metacpan.org/pod/DateTime%3A%3AFormat%3A%3AUnicode), [DateTime::Locale::FromCLDR](https://metacpan.org/pod/DateTime%3A%3ALocale%3A%3AFromCLDR), [Locale::Unicode::Data](https://metacpan.org/pod/Locale%3...

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, ...

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...

`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 ...

# 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 ...

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/R...

    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/Global_Objects/In...

    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()](https://metacpan.org/pod/Locale%3A%3AIntl#getNumberingSystems). This...

    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/Global_Objects/Intl/Locale/getNumberingSystems), and also the perl module [Locale::Intl](https://metacpan.org/pod/Locale%3A%3AIntl)

- `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 `fals...

- `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/Global_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 gi...

    See [Mozilla documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#timezone)

### Date-time component options

- `weekday`

    The representation of the weekday. Possible values are:

    - `long`

        For example: `Thursday`

    - `short`

        For example: `Thu`

    - `narrow`

        For example: `T`

        Two weekdays may have the same narrow style for some locales (e.g. `Tuesday`'s narrow style is also `T`).

- `era`

    The representation of the era. Possible values are:

    - `long`

        For example: `Anno Domini`

    - `short`

        For example: `AD`

    - `narrow`

README.md  view on Meta::CPAN

        weekday => 'long',
        year    => 'numeric',
        month   => 'long',
        day     => 'numeric',
    });
    say $fmt->format( $d ); # mercredi 10 janvier à 19:00
    my $ref = $fmt->formatToParts( $d );

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](https://metacpan.org/pod/DateTime) object, and returns an array of locale-specific tokens representing each part of the formatted date produced by this [DateTime::Format::Intl](https://metacpa...

If no [DateTime](https://metacpan.org/pod/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 ...

- `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...

# OTHER NON-CORE METHODS

## error

Sets or gets an [exception object](https://metacpan.org/pod/DateTime%3A%3AFormat%3A%3AIntl%3A%3AException)

When called with parameters, this will instantiate a new [DateTime::Format::Intl::Exception](https://metacpan.org/pod/DateTime%3A%3AFormat%3A%3AIntl%3A%3AException) object, passing it all the parameters received.

When called in accessor mode, this will return the latest [exception object](https://metacpan.org/pod/DateTime%3A%3AFormat%3A%3AIntl%3A%3AException) 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](https://metacpan.org/pod/DateTime%3A%3AFormat%3A%3AIntl%3A%3AException), this module will die with an [exception objec...

    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.
    }

## greatest\_diff

    my $fmt = DateTime::Format::Intl->new( 'fr-FR' );
    say $fmt->formatRange( $d1 => $d2 ); # 10/05/2024 - 11/05/2024
    # Found that day ('d') is the greatest difference between the two datetimes
    my $component = $fmt->greatest_diff; # d

Read-only method.

Returns a string representing the component that is the greatest difference between two datetimes.



( run in 0.584 second using v1.01-cache-2.11-cpan-39bf76dae61 )