IntlDateFormatter::formatObject

datefmt_format_object

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::formatObject -- datefmt_format_objectFormatea un objeto

Descripción

Estilo orientado a objetos

public static IntlDateFormatter::formatObject(IntlCalendar|DateTimeInterface $datetime, array|int|string|null $format = null, ?string $locale = null): string|false

Estilo procedimental

datefmt_format_object(IntlCalendar|DateTimeInterface $datetime, array|int|string|null $format = null, ?string $locale = null): string|false

Esta función permite el formato de un objeto IntlCalendar o de un objeto DateTime sin haber creado previamente un objeto IntlDateFormatter.

El objeto IntlDateFormatter temporal creado tomará el desplazamiento horario desde el objeto pasado. La base de datos de desplazamientos horarios interna a PHP no será utilizada - ICU será utilizado en su lugar. El identificador de desplazamiento horario utilizado en los objetos DateTime debe existir también en la base de datos ICU.

Parámetros

datetime

Un objeto de tipo IntlCalendar o de tipo DateTime. La información de desplazamiento horario en el objeto será utilizada.

format

Formato de la fecha/hora. Puede ser un array con dos elementos (primero el estilo de la fecha, luego el estilo de la hora, utilizando una de las constantes siguientes: IntlDateFormatter::NONE, IntlDateFormatter::SHORT, IntlDateFormatter::MEDIUM, IntlDateFormatter::LONG, IntlDateFormatter::FULL), un tipo int con el valor de una de estas constantes (en cuyo caso, será utilizado tanto para la fecha como para la hora), o un tipo string con el formato descrito en la » documentación ICU. Si null es proporcionado, el estilo por defecto será utilizado.

locale

La configuración local a utilizar, o null para utilizar la configuración local por defecto.

Valores devueltos

Una cadena de caracteres que contiene el resultado o false si ocurre un error.

Ejemplos

Ejemplo #1 Ejemplo con IntlDateFormatter::formatObject()

<?php
/* El desplazamiento horario por defecto no es significativo;
se toma desde el objeto */
ini_set('date.timezone', 'UTC');

/* La configuración local por defecto se toma desde la configuración ini */
ini_set('intl.default_locale', 'fr_FR');

$cal = IntlCalendar::fromDateTime("2013-06-06 17:05:06 Europe/Dublin");
echo
"défault :\n\t",
IntlDateFormatter::formatObject($cal),
"\n";

echo
"long \$format (complet) :\n\t",
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL),
"\n";

echo
"array \$format (ninguno, complet) :\n\t",
IntlDateFormatter::formatObject($cal, array(
IntlDateFormatter::NONE,
IntlDateFormatter::FULL)),
"\n";

echo
"string \$format (d 'de' MMMM y):\n\t",
IntlDateFormatter::formatObject($cal, "d 'de' MMMM y", 'en_US'),
"\n";

echo
"con DateTime :\n\t",
IntlDateFormatter::formatObject(
new
DateTime("2013-09-09 09:09:09 Europe/Madrid"),
IntlDateFormatter::FULL,
'es_ES'),
"\n";

El ejemplo anterior mostrará :

défault :
    6 junio 2013 17:05:06
long $format (complet):
    jueves 6 junio 2013 17:05:06 hora de verano irlandesa
array $format (ninguno, complet):
    17:05:06 hora de verano irlandesa
string $format (d 'de' MMMM y):
    6 de June 2013
con DateTime :
    lunes, 9 de septiembre de 2013 09:09:09 Hora de verano de Europa central

add a note

User Contributed Notes 4 notes

up
1
Anonymous
2 years ago
`format` vs static `formatObject`

** The `formatObject` is NOT slower! (on PHP 5.5) **

Use either the `format` method or the static `formatObject`.

Since `formatObject` is doing the work of `new IntlDateFormatter` with the provided pattern, the instantiation line must be included in the loop!

Another debunked flawed false test!

php -v
PHP 5.5.26-1+deb.sury.org~precise+1 (cli) (built: Jun 15 2015 10:04:01)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
with Xdebug v2.3.2, Copyright (c) 2002-2015, by Derick Rethans

<?php
date_default_timezone_set
('America/Los_Angeles');
$n = 3000;

$dt = new DateTime('2015-01-03 12:32:44');

$time[] = microtime(true);
for(
$i=0;$i<$n;$i++) {
$a = IntlDateFormatter::formatObject($dt, 'MMMM dd', 'hu_HU');
}
echo
"$a\n";
$time[] = microtime(true);
for(
$i=0;$i<$n;$i++) {
$df = new IntlDateFormatter('hu_HU', IntlDateFormatter::SHORT, IntlDateFormatter::NONE, null, null, 'MMMM dd');
$a = $df->format($dt);
}
echo
"$a\n";
$time[] = microtime(true);

for(
$j=1;$j<count($time);$j++) {
printf("%fs\n", $time[$j]-$time[$j-1]);
}
?>

`formatObject` : 0.336579s
`format` : 0.391158s
up
2
raf at sns dot pm
3 years ago
If you want to format a date according to a specific scheme and in a local language, here is the link to the reference of the formatting codes to use, I did not find it directly in the documentation:
https://unicode-org.github.io/icu/userguide/format_parse/datetime/#date-field-symbol-table
Here is a test using a DateTime object :

<?php

// must be required by the server
date_default_timezone_set( 'Europe/Paris' );

// instantiate a new DateTime object
$dateTimeObj = new DateTime('now', new DateTimeZone('Europe/Paris'));

// format the date with a specific scheme
// the 3 parameters are [ DateTimeObject, ICU Scheme, locale code string ]
$dateFromatted = IntlDateFormatter::formatObject( $dateTimeObj, "eee d MMMM y à HH:mm", 'fr' );

// test :
echo ucwords($dateFromatted);
// output : Jeu. 7 Avril 2022 à 04:36 // formatted as i want

?>
up
-3
ferenczi dot krisztian at gmail dot com
9 years ago
`format` vs static `formatObject`

The `formatObject` is slower! `format` is more then 10-13 times faster! (on PHP 5.5) Use the `format` method instead of the static `formatObject`.

php -v
PHP 5.5.26-1+deb.sury.org~precise+1 (cli) (built: Jun 15 2015 10:04:01)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
with Xdebug v2.3.2, Copyright (c) 2002-2015, by Derick Rethans

<?php
$n
= 3000;

$dt = new \DateTime('2015-01-03 12:32:44');
$df = new IntlDateFormatter('hu_HU', IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
$df->setPattern('MMMM dd');

$time[] = microtime(true);
for(
$i=0;$i<$n;$i++) {
$a = IntlDateFormatter::formatObject($dt, 'MMMM dd', 'hu_HU');
}
echo
"$a\n";
$time[] = microtime(true);
for(
$i=0;$i<$n;$i++) {
$a = $df->format($dt);
}
echo
"$a\n";
$time[] = microtime(true);

for(
$j=1;$j<count($time);$j++) {
printf("%fs\n", $time[$j]-$time[$j-1]);
}
?>

`formatObject` : 0.458248 s
`format` : 0.033759 s
up
-3
sebastian at huehnerhose dot de
8 years ago
It's still slower on php7.1, but not that dramatic anymore, here I got something around 5times slower
To Top