Esta tradução está incompleta. Por favor, ajude a traduzir este artigo.
O método toLocaleDateString()
retorna uma string com a representação de parte da data baseando-se no idioma. Os novos argumentos lacales
e options
deixam as aplicações especificarem o idioma cujas convenções de formatação devem ser usadas e permitem customizar o comportamento da função. Em implementações antigas, nas quais ignoram os argumentos locales
e options
, o locale usado e a forma da string retornada são inteiramente dependente da implementação nativa.
Sintáxe
dateObj.toLocaleDateString([locales [, options]])
Parametros
Verifique a seção Compatibilidade entre navegadores para ver quais navegadores dão suporte aos argumentos locales
e options
, e o Example: Verificação para suporte dos argumentos locales
e options
para detectar a funcionalidade.
locales
-
Optional. A string with a BCP 47 language tag, or an array of such strings. Unicode extension are supported (for example
"en-US-u-ca-buddhist"
). For the general form and interpretation of thelocales
argument, see the Intl page. The following Unicode extension keys are allowed:nu
- Numbering system. Possible values include:
"arab"
,"arabext"
,"bali"
,"beng"
,"deva"
,"fullwide"
,"gujr"
,"guru"
,"hanidec"
,"khmr"
,"knda"
,"laoo"
,"latn"
,"limb"
,"mlym"
,"mong"
,"mymr"
,"orya"
,"tamldec"
,"telu"
,"thai"
,"tibt"
. ca
- Calendar. Possible values include:
"buddhist"
,"chinese"
,"coptic"
,"ethioaa"
,"ethiopic"
,"gregory"
,"hebrew"
,"indian"
,"islamic"
,"islamicc"
,"iso8601"
,"japanese"
,"persian"
,"roc"
. hc
- Hour cycle. Possible values include:
"h11"
,"h12"
,"h23"
,"h24"
.
options
-
Optional. An object with some or all of the following properties:
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 the Intl page. timeZone
- The time zone to use. The only value implementations must recognize is
"UTC"
; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as"Asia/Shanghai"
,"Asia/Kolkata"
,"America/New_York"
. hour12
- Whether to use 12-hour time (as opposed to 24-hour time). Possible values are
true
andfalse
; the default is locale dependent. This option overrides thehc
language tag and/or thehourCycle
option in case both are present. hourCycle
- The hour cycle to use. Possible values are
"h11"
,"h12"
,"h23"
, or"h24"
. This option overrides thehc
language tag, if both are present, and thehour12
option takes precedence in case both options have been specified. formatMatcher
- The format matching algorithm to use. Possible values are
"basic"
and"best fit"
; the default is"best fit"
. See the following paragraphs for information about the use of this property.
The following properties describe the date-time components to use in formatted output, and their desired representations. Implementations are required to support at least the following subsets:
weekday
,year
,month
,day
,hour
,minute
,second
weekday
,year
,month
,day
year
,month
,day
year
,month
month
,day
hour
,minute
,second
hour
,minute
Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. Two algorithms are available for this negotiation and selected by the
formatMatcher
property: A fully specified"basic"
algorithm and an implementation-dependent"best fit"
algorithm.weekday
- The representation of the weekday. Possible values are
"narrow"
,"short"
,"long"
. era
- The representation of the era. Possible values are
"narrow"
,"short"
,"long"
. year
- The representation of the year. Possible values are
"numeric"
,"2-digit"
. month
- The representation of the month. Possible values are
"numeric"
,"2-digit"
,"narrow"
,"short"
,"long"
. day
- The representation of the day. Possible values are
"numeric"
,"2-digit"
. hour
- The representation of the hour. Possible values are
"numeric"
,"2-digit"
. minute
- The representation of the minute. Possible values are
"numeric"
,"2-digit"
. second
- The representation of the second. Possible values are
"numeric"
,"2-digit"
. timeZoneName
- The representation of the time zone name. Possible values are
"short"
,"long"
.
undefined
, mas se as propriedades weekday
, year
, month
, day
são todas undefined
, então year
, month
and day
são assumidos como "numeric
".Return value
Uma representação em string de parte da data dada a instância Date
de acordo com as convenções específicas do idioma.
Examples
Usando toLocaleDateString()
Em uso básico sem especificação de locale, uma string formatada no padrão do locale e com as opções padrões é retornada.
var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0)); // toLocaleDateString() sem argumentos depende da implementação, // o locale padrão, e o time zone padrão console.log(date.toLocaleDateString()); // → "12/11/2012" se rondando em locale en-US com time zone de America/Los_Angeles
Checagem para o suporte dos argumentos locales
e options
Os argumentos locales
e options
não são suportados em todos os browser ainda. Para verificar se uma uma implementação já suporta eles, você pode usar o requisito de que tags de idioma ilegal são rejeitadas com uma exceção RangeError
:
function toLocaleDateStringSupportsLocales() { try { new Date().toLocaleDateString('i'); } catch (e) { return e.name === 'RangeError'; } return false; }
Usando locales
Esse exemplo mostra algumas das variações em formatos de data localizados. A fim de obter oformato do idioma usado na interface de usuário da usa aplicação, certifique-se de especificar esse idioma (e possivelmente algumas outros idiomas de reserva) usando o argumento locales
:
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// os formatos abaixo assumem o time zone local do locale;
// America/Los_Angeles for the US
// Inglês americano usa a ordem mês-dia-ano
console.log(date.toLocaleDateString('en-US'));
// → "12/19/2012"
// Inglês Britânico usa a ordem dia-mês-ano
console.log(date.toLocaleDateString('en-GB'));
// → "20/12/2012"
// Coreano usa a ordem ano-mês-dia
console.log(date.toLocaleDateString('ko-KR'));
// → "2012. 12. 20."
// Árabe na maioria dos países de língua árabe usa dígitos árabes reais
console.log(date.toLocaleDateString('ar-EG'));
// → "٢٠/١٢/٢٠١٢"
// para Japonês, aplicações podem querer usar o calendário japonês,
// onde 2012 foi o ano 24 da era Heisei
console.log(date.toLocaleDateString('ja-JP-u-ca-japanese'));
// → "24/12/20"
// quando um idioma que pode não ser suportado é requerido, tal como
// Balinês, inclua um idioma de reserva, nesse caso Indonésio
console.log(date.toLocaleDateString(['ban', 'id']));
// → "20/12/2012"
Usando options
O resultados gerados por toLocaleDateString()
podem ser customizado usando o argumento options
:
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // requer um dia da semana jutamente com uma data longa var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; console.log(date.toLocaleDateString('de-DE', options)); // → "Donnerstag, 20. Dezember 2012" // uma aplicação pode querer usar UTC e fazê-lo visível options.timeZone = 'UTC'; options.timeZoneName = 'short'; console.log(date.toLocaleDateString('en-US', options)); // → "Thursday, December 20, 2012, GMT"
Performance
Ao formatar um grande número de datas, é melhor criar um objeto Intl.DateTimeFormat
e usar a função fornecido porsua propriedade format
.
Specifications
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
locales and options arguments |
24 [1] | 29 (29) | 11 | 15 | 10 |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
locales and options arguments |
Não suportado | 26 | Não suportado | Não suportado | Não suportado | 10 |
[1] Chrome 24 also added support for passing timeZones other than UTC.