Funções de Data/Hora
PHP Manual

strftime

(PHP 4, PHP 5, PHP 7)

strftimeFormata uma hora/data de acordo com as configurações locais

Descrição

string strftime ( string $format [, int $timestamp ] )

Formata uma hora/data local de acordo com a configuração do idioma. Nome do mês e dia da semana e outras strings respeitam o idioma corrente definido com a função setlocale().

Note que nem todas as conversões especificadas pela sua biblioteca C, serão suportadas pela função do PHP strftime(). Além disso, nem todas as plataformas suportam timestamps negativos, então sua faixa de datas pode ser limitada a um valor menor que a época Unix. Isto significa e.g. %e, %T, %R e %D (e outras mais) e datas anteriores a Jan 1, 1970 não funcionarão no Windows, algumas distribuições Linux, e outros sistemas operacionais. Para sistemas Windows, um resumo completo dos especificadores de conversão suportados podem ser encontrados em » MSDN .

Parâmetros

format

Os seguintes caracteres são reconhecidos no string do parâmetro format
format Descrição Exemplo de valores retornados
Dia --- ---
%a Representação textual abreviada do dia Sun até Sat
%A Representação textual completa do dia Sunday até Saturday
%d Dia do mês, com dois dígitos (com zeros à esquerda) 01 a 31
%e Dia do mês com um dígito, precedido com um espaço. Não implementado como descrito no Windows. Veja abaixo para mais informações. 1 a 31
%j Dia do ano, com 3 dígitos e zeros à esquerda 001 a 366
%u Representação numérica, do dia da semana, compatível com a ISO-8601 1 (para Monday) até 7 (para Sunday)
%w Representação numérica do dia da semana 0 (para Sunday) até 6 (para Saturday)
Semana --- ---
%U Número da semana de um dado ano, iniciado com o primeiro Domingo sendo a primeira semana 13 (como a 13ª semana completa do ano)
%V Número da semana, compatível com a ISO-8601:1988 de um dado ano, iniciada com a primeira semana do ano com pelo menos 4 finais de semana, sendo a Segunda-feira como o início da semana. 01 até 53 (onde 53 é responsável por uma sobreposição)
%W Representação numérica da semana do ano, começando pela primeira Segunda-feira como primeira semana 46 (como a 46ª semana do do ano iniciando na Segunda-feira)
Mês --- ---
%b Nome do mês abreviado, baseado no idioma Jan até Dez
%B Nome completo do mês, baseado no idioma Janeiro até Dezembro
%h Nome do mês abreviado, baseado no idioma (sinônimo de %b) Jan até Dez
%m Representação com dois dígitos do mês 01 (para January) through 12 (para December)
Ano --- ---
%C Representação, com dois dígitos, do século (ano dividido por 100, truncado como inteiro) 19 para o século 20
%g Representação do ano, com dois dígitos, seguindo o padrão ISO-8601:1988 (veja %V) Exemplo: 09 de January 6, 2009
%G Versão de 4 dígitos de %g Exemplo: 2008 de January 3, 2009
%y Representação, com dois dígitos, do ano Exemplo: 09 de 2009, 79 de 1979
%Y Representação, com quatro dígitos, do ano Exemplo: 2038
Hora --- ---
%H Representação, com dois dígitos, da hora no formato 24 horas 00 até 23
%k Representação, com dois dígitos, da hora no formato 24 horas, com um espaço precedendo aqueles com somente um dígito 0 até 23
%I Representação, com dois dígitos, da hora no formato 12 horas 01 até 12
%l ('L' minúsculo) Representação, com dois dígitos, da hora no formato 12 horas, com um espaço precedendo aqueles com somente um dígito 1 até 12
%M Representação, com dois dígitos, do minuto 00 até 59
%p 'AM' ou 'PM' maiúsculo baseado na hora informada Exemplo: AM para 00:31, PM para 22:23
%P 'am' ou 'pm' maiúsculo baseado na hora informada Exemplo: am para 00:31, pm para 22:23
%r O mesmo que "%I:%M:%S %p" Exemplo: 09:34:17 PM de 21:34:17
%R O mesmo que "%H:%M" Exemplo: 00:35 de 12:35 AM, 16:44 de 4:44 PM
%S Representação, com dois dígitos, do segundo 00 até 59
%T O mesmo que "%H:%M:%S" Exemplo: 21:34:17 para 09:34:17 PM
%X Representação escolhida baseada no idioma, sem a data Exemplo: 03:59:16 ou 15:59:16
%z O deslocamento do fuso horário. Não implementado como descrito no Windows. Veja mais informações a seguir. Exemplo: -0500 para hora à leste dos EUA
%Z A abreviação do fuso horário. Não implementado como descrito no Windows. Veja mais informações a seguir. Exemplo: EST para Eastern Time
Carimbos de Data e Hora --- ---
%c Carimbo escolhido de data e hora baseado no idioma Exemplo: Ter Fev 5 00:45:10 2009 de February 5, 2009 at 12:45:10 AM
%D O mesmo que "%m/%d/%y" Exemplo: 02/05/09 de February 5, 2009
%F O mesmo que "%Y-%m-%d" (geralmente utilizado em carimbos de data em bancos de dados) Exemplo: 2009-02-05 de February 5, 2009
%s Timestamp Unix Epoch Time (o mesmo que a função time() function) Exemplo: 305815200 de September 10, 1979 08:40:00 AM
%x Carimbo escolhido de data e hora baseado no idioma, sem a hora Exemplo: 02/05/09 de February 5, 2009
Miscelânea --- ---
%n Uma nova linha ("\n") ---
%t Um caractere TAB ("\t") ---
%% Um caractere literal de porcento ("%") ---

Tamanho máximo deste parâmetro é 1023 caracteres.

Aviso

Contrário a ISO-9899:1999, o sistema Sun Solaris começa a semana no Domingo, como 1. Resultando em %u não funcionando como descrito neste manual.

Aviso

Somente no Windows:

O modificador %e não possui suporte a implementação desta função no Windows. Para conseguir este valor, o modificador %#d pode ser utilizado em substituição. O exemplo a seguir ilustra como escrever uma função com compatibilidade multiplataforma.

Os modificadores %z e %Z retornam o nome do fuso horário em vez do deslocamento ou abreviação do mesmo.

Aviso

Somente Mac OS X: O modificador %P não têm suporte a implementação desta função no Mac OS X.

timestamp

O parâmetro opcional timestamp é um integer Unix timestamp cujo padrão é a hora local se timestamp não for informado. Em outras palavras, o padrão é o valor da função time().

Valor Retornado

Retorna uma string formatada de acordo com o format informado em timestamp ou o horário local atual se nenhum timestamp foi informado. Nomes de meses e dia da semana, e outras strings dependentes de linguagens respeitam o idioma definido com a função setlocale().

Erros

Todas as chamadas a funções de data/hora gerarão um E_NOTICE se o fuso horário não for válido, e/ou uma mensagem E_STRICT ou E_WARNING se utilizar as configurações do sistema ou a variável de ambiente TZ. Veja também date_default_timezone_set()

Como a saída depende da biblioteca C disponível, alguns especificadores de conversão não possuem suporte. No Windows, informar especificadores de conversão desconhecidos resultará em mensagens E_WARNING e retornará FALSE. Em outros sistemas operacionais você pode não receber nenhuma mensagem E_WARNING e a saída poderá conter os especificadores de conversão não convertidos.

Changelog

Versão Descrição
5.1.0

Agora lança erros E_STRICT e E_NOTICE .

Exemplos

Este exemplo funciona se você tem os respectivos idiomas instalados em seu sistema.

Exemplo #1 Exemplo da função strftime() com idiomas

<?php
setlocale
(LC_TIME"C");
echo 
strftime("%A");
setlocale(LC_TIME"fi_FI");
echo 
strftime(" in Finnish is %A,");
setlocale(LC_TIME"fr_FR");
echo 
strftime(" in French %A and");
setlocale(LC_TIME"de_DE");
echo 
strftime(" in German %A.\n");
?>

Exemplo #2 Exemplo do número de semana ISO 8601:1988

<?php
/*     December 2002 / January 2003
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     16  17  18  19  20  21  22
52     23  24  25  26  27  28  29
1      30  31   1   2   3   4   5
2       6   7   8   9  10  11  12
3      13  14  15  16  17  18  19   */

// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " strftime("%V,%G,%Y"strtotime("12/28/2002")) . "\n";

// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " strftime("%V,%G,%Y"strtotime("12/30/2002")) . "\n";

// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";



/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

Exemplo #3 Exemplo do uso do modificador %e compatível com múltiplas plataformas

<?php

// Jan 1: results in: '%e%1%' (%%, e, %%, %e, %%)
$format '%%e%%%e%%';

// Check for Windows to find and replace the %e
// modifier correctly
if (strtoupper(substr(PHP_OS03)) == 'WIN') {
    
$format preg_replace('#(?<!%)((?:%%)*)%e#''\1%#d'$format);
}

echo 
strftime($format);
?>

Exemplo #4 Mostra os formatos conhecidos e desconhecidos

<?php
// Describe the formats.
$strftimeFormats = array(
    
'A' => 'A full textual representation of the day',
    
'B' => 'Full month name, based on the locale',
    
'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
    
'D' => 'Same as "%m/%d/%y"',
    
'E' => '',
    
'F' => 'Same as "%Y-%m-%d"',
    
'G' => 'The full four-digit version of %g',
    
'H' => 'Two digit representation of the hour in 24-hour format',
    
'I' => 'Two digit representation of the hour in 12-hour format',
    
'J' => '',
    
'K' => '',
    
'L' => '',
    
'M' => 'Two digit representation of the minute',
    
'N' => '',
    
'O' => '',
    
'P' => 'lower-case "am" or "pm" based on the given time',
    
'Q' => '',
    
'R' => 'Same as "%H:%M"',
    
'S' => 'Two digit representation of the second',
    
'T' => 'Same as "%H:%M:%S"',
    
'U' => 'Week number of the given year, starting with the first Sunday as the first week',
    
'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
    
'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
    
'X' => 'Preferred time representation based on locale, without the date',
    
'Y' => 'Four digit representation for the year',
    
'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
    
'a' => 'An abbreviated textual representation of the day',
    
'b' => 'Abbreviated month name, based on the locale',
    
'c' => 'Preferred date and time stamp based on local',
    
'd' => 'Two-digit day of the month (with leading zeros)',
    
'e' => 'Day of the month, with a space preceding single digits',
    
'f' => '',
    
'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
    
'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
    
'i' => '',
    
'j' => 'Day of the year, 3 digits with leading zeros',
    
'k' => 'Hour in 24-hour format, with a space preceding single digits',
    
'l' => 'Hour in 12-hour format, with a space preceding single digits',
    
'm' => 'Two digit representation of the month',
    
'n' => 'A newline character ("\n")',
    
'o' => '',
    
'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
    
'q' => '',
    
'r' => 'Same as "%I:%M:%S %p"',
    
's' => 'Unix Epoch Time timestamp',
    
't' => 'A Tab character ("\t")',
    
'u' => 'ISO-8601 numeric representation of the day of the week',
    
'v' => '',
    
'w' => 'Numeric representation of the day of the week',
    
'x' => 'Preferred date representation based on locale, without the time',
    
'y' => 'Two digit representation of the year',
    
'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
    
'%' => 'A literal percentage character ("%")',
);

// Results.
$strftimeValues = array();

// Evaluate the formats whilst suppressing any errors.
foreach($strftimeFormats as $format => $description){
    if (
False !== ($value = @strftime("%{$format}"))){
        
$strftimeValues[$format] = $value;
    }
}

// Find the longest value.
$maxValueLength max(array_map('strlen'$strftimeValues));

// Report known formats.
foreach($strftimeValues as $format => $value){
    echo 
"Known format   : '{$format}' = "str_pad("'{$value}'"$maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}

// Report unknown formats.
foreach(array_diff_key($strftimeFormats$strftimeValues) as $format => $description){
    echo 
"Unknown format : '{$format}'   "str_pad(' '$maxValueLength), ($description " ( {$description} )" ''), "\n";
}
?>

O exemplo acima irá imprimir algo similar à:

Known format   : 'A' = 'Friday'            ( A full textual representation of the day )
Known format   : 'B' = 'December'          ( Full month name, based on the locale )
Known format   : 'H' = '11'                ( Two digit representation of the hour in 24-hour format )
Known format   : 'I' = '11'                ( Two digit representation of the hour in 12-hour format )
Known format   : 'M' = '24'                ( Two digit representation of the minute )
Known format   : 'S' = '44'                ( Two digit representation of the second )
Known format   : 'U' = '48'                ( Week number of the given year, starting with the first Sunday as the first week )
Known format   : 'W' = '48'                ( A numeric representation of the week of the year, starting with the first Monday as the first week )
Known format   : 'X' = '11:24:44'          ( Preferred time representation based on locale, without the date )
Known format   : 'Y' = '2010'              ( Four digit representation for the year )
Known format   : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
Known format   : 'a' = 'Fri'               ( An abbreviated textual representation of the day )
Known format   : 'b' = 'Dec'               ( Abbreviated month name, based on the locale )
Known format   : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
Known format   : 'd' = '03'                ( Two-digit day of the month (with leading zeros) )
Known format   : 'j' = '337'               ( Day of the year, 3 digits with leading zeros )
Known format   : 'm' = '12'                ( Two digit representation of the month )
Known format   : 'p' = 'AM'                ( UPPER-CASE "AM" or "PM" based on the given time )
Known format   : 'w' = '5'                 ( Numeric representation of the day of the week )
Known format   : 'x' = '12/03/10'          ( Preferred date representation based on locale, without the time )
Known format   : 'y' = '10'                ( Two digit representation of the year )
Known format   : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
Known format   : '%' = '%'                 ( A literal percentage character ("%") )
Unknown format : 'C'                       ( Two digit representation of the century (year divided by 100, truncated to an integer) )
Unknown format : 'D'                       ( Same as "%m/%d/%y" )
Unknown format : 'E'
Unknown format : 'F'                       ( Same as "%Y-%m-%d" )
Unknown format : 'G'                       ( The full four-digit version of %g )
Unknown format : 'J'
Unknown format : 'K'
Unknown format : 'L'
Unknown format : 'N'
Unknown format : 'O'
Unknown format : 'P'                       ( lower-case "am" or "pm" based on the given time )
Unknown format : 'Q'
Unknown format : 'R'                       ( Same as "%H:%M" )
Unknown format : 'T'                       ( Same as "%H:%M:%S" )
Unknown format : 'V'                       ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
Unknown format : 'e'                       ( Day of the month, with a space preceding single digits )
Unknown format : 'f'
Unknown format : 'g'                       ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
Unknown format : 'h'                       ( Abbreviated month name, based on the locale (an alias of %b) )
Unknown format : 'i'
Unknown format : 'k'                       ( Hour in 24-hour format, with a space preceding single digits )
Unknown format : 'l'                       ( Hour in 12-hour format, with a space preceding single digits )
Unknown format : 'n'                       ( A newline character ("\n") )
Unknown format : 'o'
Unknown format : 'q'
Unknown format : 'r'                       ( Same as "%I:%M:%S %p" )
Unknown format : 's'                       ( Unix Epoch Time timestamp )
Unknown format : 't'                       ( A Tab character ("\t") )
Unknown format : 'u'                       ( ISO-8601 numeric representation of the day of the week )
Unknown format : 'v'

Notas

Nota: %G e %V, que são baseadas nos números de semana da ISO 8601:1988, podem dar resultados inesperados (embora corretos), se o sistema numérico não for reconhecido perfeitamente. Veja exemplos da %V nesta página do manual.

Veja Também


Funções de Data/Hora
PHP Manual