Search code examples
javascripticuintlecmascript-intl

Javascript Intl DatetimeFormatter as (ISO_8601|custom) output pattern


I want to use Intl.DateTimeFormat but with custom pattern for output. I use this method for php version of ICU dateformat and it's work well.

$fmt = datefmt_create(
    'fa_IR@calendar=persian',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'Asia/Tehran',
    IntlDateFormatter::TRADITIONAL,
    'EEEE d MMMM yyyy HH:mm' // as ISO_8601
);

echo datefmt_format($fmt, time()) . "\n";
// پنجشنبه ۱۰ اردیبهشت ۱۳۹۴ ۱۲:۱۲

How can i set pattern as ICU documentation in Intl.DateTimeFormat like php version of ICU date time formatter.

My javascript code

console.log(new Intl.DateTimeFormat('fa-IR-u-ca-persian').format(new Date()));

How can iset ISO_8601 pattern in my javascript format pattern like EEEE d MMMM yyyy HH:mm or MM yy dd or etc ?

ISO_8601

PHP IntlDateFormatter::format

ICU Date formatter

ICU Date formats


Solution

  • You can't.

    The idea implemented by Intl is to give you the "right" format for whatever you request, by the terms of the locale you provide, possibly subject to Unicode extension subtags and similar to configure certain behavioral nuances. Intl doesn't provide any way to specify and use particular formatting patterns. ISO-8601 format is not something that's guaranteed to be the appropriate format for any particular locale, so you can't use Intl to produce it.

    If you want to format a date according to a particular pattern slotting in the desired numeric values, you'll have to implement it yourself by calling Date.prototype.getMonth and similar functions to get numbers, then slot them into a provided pattern.