aboutsummaryrefslogtreecommitdiff
path: root/files/pt-br/web/javascript/reference/global_objects/date/tolocalestring/index.html
blob: 06d9b1f30ccef0a9f92551c67d21f1962c04255a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
---
title: Date.prototype.toLocaleString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
tags:
  - Internacionalização
  - JavaScript
  - Prototype
  - Referencia
  - data
  - i18n
  - metodo
translation_of: Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
---
<div>{{JSRef}}</div>

<p>O método <strong><code>toLocaleString()</code></strong> retorna uma <em>string</em><strong> </strong>com uma representação sensível ao idioma da data presente na mesma. Os novos argumentos <code>locales</code> e <code>options</code> permitem que as aplicações especifiquem o idioma cujas convenções de formatação devem ser utilizadas e personalizar o comportamento do método. Em implementações antigas, que ignoram os argumentos <code>locales</code> and <code>options</code>, o local utilizado e o formato da <em>string</em> retornada são completamente dependentes da implementação.</p>

<div>{{EmbedInteractiveExample("pages/js/date-tolocalestring.html")}}</div>

<p class="hidden">O código-fonte deste exemplo interativo está armazenado em um repositório do GitHub. Se você quiser contribuir com o projeto de exemplos interativos, por favor clone o repositório <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e envie-nos <em>pull requests</em>.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox"><var>dateObj</var>.toLocaleString([<var>locales</var>[, <var>options</var>]])</pre>

<h3 id="Parameters">Parameters</h3>

<p>Check the <a href="#Browser_Compatibility">Browser compatibility</a> section to see which browsers support the <code>locales</code> and <code>options</code> arguments, and the <a href="#Example:_Checking_for_support_for_locales_and_options_arguments">Example: Checking for support for <code>locales</code> and <code>options</code> arguments</a> for feature detection.</p>

<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat', 'Parameters')}}</div>

<p>The default value for each date-time component property is {{jsxref("undefined")}}, but if the <code>weekday</code>, <code>year</code>, <code>month</code>, <code>day</code>, <code>hour</code>, <code>minute</code>, <code>second</code> properties are all {{jsxref("undefined")}}, then <code>year</code>, <code>month</code>, <code>day</code>, <code>hour</code>, <code>minute</code>, and <code>second</code> are assumed to be <code>"numeric"</code>.</p>

<h3 id="Return_value">Return value</h3>

<p>A string representing the given date according to language-specific conventions.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Using_toLocaleString()">Using <code>toLocaleString()</code></h3>

<p>In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.</p>

<pre class="brush: js">var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));

// toLocaleString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleString());
// → "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles
</pre>

<h3 id="Checking_for_support_for_locales_and_options_arguments">Checking for support for <code>locales</code> and <code>options</code> arguments</h3>

<p>The <code>locales</code> and <code>options</code> arguments are not supported in all browsers yet. To check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a {{jsxref("RangeError")}} exception:</p>

<pre class="brush: js">function toLocaleStringSupportsLocales() {
  try {
    new Date().toLocaleString('i');
  } catch (e) {
    return e instanceof RangeError;
  }
  return false;
}
</pre>

<h3 id="Using_locales">Using <code>locales</code></h3>

<p>This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the <code>locales</code> argument:</p>

<pre class="brush: js">var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US

// US English uses month-day-year order and 12-hour time with AM/PM
console.log(date.toLocaleString('en-US'));
// → "12/19/2012, 7:00:00 PM"

// British English uses day-month-year order and 24-hour time without AM/PM
console.log(date.toLocaleString('en-GB'));
// → "20/12/2012 03:00:00"

// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(date.toLocaleString('ko-KR'));
// → "2012. 12. 20. 오후 12:00:00"

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleString('ar-EG'));
// → "<span dir="rtl">٢٠‏/١٢‏/٢٠١٢ ٥:٠٠:٠٠ ص</span>"

// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleString('ja-JP-u-ca-japanese'));
// → "24/12/20 12:00:00"

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleString(['ban', 'id']));
// → "20/12/2012 11.00.00"
</pre>

<h3 id="Using_options">Using <code>options</code></h3>

<p>The results provided by <code>toLocaleString()</code> can be customized using the <code>options</code> argument:</p>

<pre class="brush: js">var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// request a weekday along with a long date
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(date.toLocaleString('de-DE', options));
// → "Donnerstag, 20. Dezember 2012"

// an application may want to use UTC and make that visible
options.timeZone = 'UTC';
options.timeZoneName = 'short';
console.log(date.toLocaleString('en-US', options));
// → "Thursday, December 20, 2012, GMT"

// sometimes even the US needs 24-hour time
console.log(date.toLocaleString('en-US', { hour12: false }));
// → "12/19/2012, 19:00:00"
</pre>

<h3 id="Avoid_comparing_formatted_date_values_to_static_values">Avoid comparing formatted date values to static values</h3>

<p>Most of the time, the formatting returned by <code>toLocaleString()</code> is consistent. However, this might change in the future and isn't guaranteed for all languages — output variations are by design and allowed by the specification. Most notably, the IE and Edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text.</p>

<p>For this reason you cannot expect to be able to compare the results of <code>toLocaleString()</code> to a static value:</p>

<pre class="brush: js; example-bad">"1.1.2019, 01:00:00" === new Date("2019-01-01T00:00:00.000000Z").toLocaleString();
// true in Firefox and others
// false in IE and Edge</pre>

<div class="blockIndicator note">
<p><strong>Note</strong>: See also this <a href="https://stackoverflow.com/questions/25574963/ies-tolocalestring-has-strange-characters-in-results">StackOverflow thread</a> for more details and examples.</p>
</div>

<h2 id="Performance">Performance</h2>

<p>When formatting large numbers of dates, it is better to create an {{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}} object and use the function provided by its {{jsxref("DateTimeFormat.prototype.format", "format")}} property.</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES1')}}</td>
   <td>{{Spec2('ES1')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.0.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.9.5.5', 'Date.prototype.toLocaleString')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-date.prototype.tolocalestring', 'Date.prototype.toLocaleString')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-date.prototype.tolocalestring', 'Date.prototype.toLocaleString')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES Int 1.0', '#sec-13.3.1', 'Date.prototype.toLocaleString')}}</td>
   <td>{{Spec2('ES Int 1.0')}}</td>
   <td>Defines <code>locales</code> and <code>options</code> arguments.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES Int 2.0', '#sec-13.3.1', 'Date.prototype.toLocaleString')}}</td>
   <td>{{Spec2('ES Int 2.0')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES Int Draft', '#sec-Date.prototype.toLocaleString', 'Date.prototype.toLocaleString')}}</td>
   <td>{{Spec2('ES Int Draft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>

<p>{{Compat("javascript.builtins.Date.toLocaleString")}}</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li>
 <li>{{jsxref("Date.prototype.toLocaleDateString()")}}</li>
 <li>{{jsxref("Date.prototype.toLocaleTimeString()")}}</li>
 <li>{{jsxref("Date.prototype.toString()")}}</li>
</ul>