IntlDateFormatter::format

datefmt_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::format -- datefmt_formatFormata data/horário como uma string

Descrição

Estilo orientado a objetos

public IntlDateFormatter::format(IntlCalendar|DateTimeInterface|array|string|int|float $datetime): string|false

Estilo procedural

Formata o valor de data/horário como uma string.

Parâmetros

formatter

O recurso de formatador de data.

datetime

O valor a ser formatado. Pode ser um objeto DateTimeInterface, um objeto IntlCalendar, um valor do tipo numeric representando um número (possivelmente fracionário) de segundos desde a época ou um array no formato da saída de localtime().

Se um objeto DateTime ou IntlCalendar for passado, seu fuso horário não será considerado. O objeto será formatado usando o fuso horário configurado pelo formatador. Se for desejado usar o fuso horário do objeto a ser formatado, IntlDateFormatter::setTimeZone() deve ser chamada antes com o fuso horário do objeto. Alternativamente, a função estática IntlDateFormatter::formatObject() pode ser usada em seu lugar.

Valor Retornado

A string formatada ou, se ocorrer um erro, false.

Registro de Alterações

Versão Descrição
7.1.5 Suporte para fornecer objetos DateTimeInterface ao parâmetro datetime foi adicionado. Anteriormente, somente objetos DateTime eram suportados.
PECL 3.0.0 Suporte para fornecer objetos IntlCalendar ao parâmetro datetime foi adicionado.

Exemplos

Exemplo #1 Exemplo de datefmt_format()

<?php
$fmt
= datefmt_create(
'pt_BR',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Sao_Paulo',
IntlDateFormatter::GREGORIAN
);
echo
'Primeira saída formatada é ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Sao_Paulo',
IntlDateFormatter::GREGORIAN
);
echo
'Segunda saída formatada é ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'pt_BR',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Sao_Paulo',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo
'Primeira saída formatada com modelo é ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Sao_Paulo',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo
"Segunda saída formatada com modelo é " . datefmt_format($fmt, 0);
?>

Exemplo #2 Exemplo OO

<?php
$fmt
= new IntlDateFormatter(
'pt_BR',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Sao_Paulo',
IntlDateFormatter::GREGORIAN
);
echo
'Primeira saída formatada é ' . $fmt->format(0), "\n";

$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Sao_Paulo',
IntlDateFormatter::GREGORIAN
);
echo
'Segunda saída formatada é ' . $fmt->format(0), "\n";

$fmt = new IntlDateFormatter(
'pt_BR',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Sao_Paulo',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo
'Primeira saída formatada com modelo é ' . $fmt->format(0), "\n";

$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Sao_Paulo',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo
'Segunda saída formatada com modelo é ' . $fmt->format(0), "\n";
?>

O exemplo acima produzirá:

Primeira saída formatada é quarta-feira, 31 de dezembro de 1969 21:00:00 Horário Padrão de Brasília
Segunda saída formatada é Mittwoch, 31. Dezember 1969 um 21:00:00 Brasília-Normalzeit
Primeira saída formatada com modelo é 12/31/1969
Segunda saída formatada com modelo é 12/31/1969

Exemplo #3 Com objeto IntlCalendar

<?php
$tz
= reset(iterator_to_array(IntlTimeZone::createEnumeration('FR')));
$formatter = IntlDateFormatter::create(
'fr_FR',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
$tz,
IntlDateFormatter::GREGORIAN
);

$cal = IntlCalendar::createInstance($tz, '@calendar=islamic-civil');
$cal->set(IntlCalendar::FIELD_MONTH, 8); //9º mês, Ramadã
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 1); //1º dia
$cal->clear(IntlCalendar::FIELD_HOUR_OF_DAY);
$cal->clear(IntlCalendar::FIELD_MINUTE);
$cal->clear(IntlCalendar::FIELD_SECOND);
$cal->clear(IntlCalendar::FIELD_MILLISECOND);

echo
"Neste ano islâmico, o Ramadã começou/começará em:\n\t",
$formatter->format($cal), "\n";

//O fuso horário do formatador será o o utilizado:
$formatter->setTimeZone('Asia/Tokyo');
echo
"Após alterar o fuso horário:\n\t",
$formatter->format($cal), "\n";

O exemplo acima produzirá:

Neste ano islâmico, o Ramadã começou/começará em:
    mardi 9 juillet 2013 19:00:00 heure avancée d’Europe centrale
Após alterar o fuso horário:
    mercredi 10 juillet 2013 02:00:00 heure normale du Japon

Veja Também

add a note add a note

User Contributed Notes 3 notes

up
16
mail dot dennisbecker at gmail dot com
11 years ago
You should know that PHPs IntlDateFormatter class uses ISO date format codes instead of PHPs date() format codes. It is not really clear mentioned from my point of view.

A good list to find ISO codes is available at http://framework.zend.com/manual/1.12/en/zend.date.constants.html#zend.date.constants.selfdefinedformats and such a list should be added here, too.
up
7
con at bartrail dot de
12 years ago
I hope this will save some time for others who have to struggle with different php versions on dev and prod plattform in the future:

when formatting a DateTime object with a *custom pattern*, be sure to use a timestamp to pass at the IntlDateFormatter::format in order to have it working on different php versions:

Example for PHP Version 5.3.5-1ubuntu7.2 (my dev machine):
<?php
$date
= new \DateTime();

$dateFormatter = \IntlDateFormatter::create(
  \
Locale::getDefault(),
  \
IntlDateFormatter::NONE,
  \
IntlDateFormatter::NONE,
  \
date_default_timezone_get(),
  \
IntlDateFormatter::GREGORIAN,
 
'EEEE'
);

var_dump($dateFormatter->format($date)); // string(6) "Monday"
?>

Example for PHP Version 5.3.2-1ubuntu4.9 (the prod server):
<?php
// same formatting as above

var_dump($dateFormatter->format($date)); // bool(false)
?>

When using $dateFormatter->format($date->getTimestamp()), you'll always get the formatted and localized string instead of a false.
up
-1
alex
13 years ago
It's important to note that a conversion of timezones will be made from the default timezone (date_default_timezone_set()) and the timezone you passed in the constructor (or datefmt_create()).

If you are inserting the dates into your database as UTC time, make sure to set date_default_timezone_set to UTC as well (or any other timezone, but they need to be the same). Once you call ::format, you will get the converted time.
To Top