aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/html/element/input/date/index.html
blob: 43675823de519c969b4c1bcc482ab59e70cf6363 (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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
---
title: <input type="date">
slug: Web/HTML/Element/Input/date
tags:
  - Element
  - HTML
  - HTML forms
  - Input
  - Input Element
  - Input Type
  - Reference
translation_of: Web/HTML/Element/input/date
---
<div>{{HTMLRef}}</div>

<p><span class="seoSummary"><strong><code>date</code></strong> 유형의 {{HTMLElement("input")}} 요소는 유효성 검증을 포함하는 텍스트 상자 또는 특별한 날짜 선택 인터페이스를 사용해 날짜를 입력할 수 있는 입력 칸을 생성합니다.</span></p>

<p>입력 칸의 값은 연, 월, 일을 포함하지만 시간은 포함하지 않습니다. {{HTMLElement("input/time", "time")}}{{HTMLElement("input/datetime-local", "datetime-local")}} 입력 유형이 시간과 시간+날짜 조합을 지원합니다.</p>

<div>{{EmbedInteractiveExample("pages/tabbed/input-date.html", "tabbed-shorter")}}</div>

<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div>

<p>입력 UI는 브라우저마다 다릅니다. {{anch("브라우저 호환성")}}에서 더 자세한 정보를 알아보세요. 날짜 입력 유형을 지원하지 않는 브라우저에서는 우아하게 <code><a href="/ko/docs/Web/HTML/Element/input/text">&lt;input type="text"&gt;</a></code>로 저하됩니다.</p>

<p>날짜 선택을 위한 별도의 인터페이스를 갖춘 브라우저 중, Chrome과 Opera는 다음과 같은 모양의 달력을 보여줍니다.</p>

<p><img alt="A textbox containing “dd/mm/yyyy”, an increment/decrement button combo, and a downward arrow that opens into a calendar control." src="https://mdn.mozillademos.org/files/14909/date-picker-chrome.png" style="display: block; height: 220px; margin: 0px auto; width: 275px;"></p>

<p>구 Edge의 컨트롤입니다.</p>

<p><img alt="A textbox containing “mm/dd/yyyy”, but when interacted with, opens a tri-column date selector." src="https://mdn.mozillademos.org/files/14911/date-picker-edge.png" style="display: block; margin: 0 auto;"></p>

<p>Firefox의 날짜 컨트롤입니다.</p>

<p><img alt="Another “dd/mm/yyyy” textbox that expands into a selectable calendar control." src="https://mdn.mozillademos.org/files/15644/firefox_datepicker.png" style="display: block; margin: 0 auto;"></p>

<table class="properties">
 <tbody>
  <tr>
   <td><strong>{{anch("값")}}</strong></td>
   <td>YYYY-MM-DD 형식으로 날짜를 나타내거나, 빈 {{domxref("DOMString")}}.</td>
  </tr>
  <tr>
   <td><strong>이벤트</strong></td>
   <td>{{domxref("HTMLElement/change_event", "change")}}, {{domxref("HTMLElement/input_event", "input")}}</td>
  </tr>
  <tr>
   <td><strong>지원하는 공통 특성</strong></td>
   <td>{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("readonly", "input")}}, {{htmlattrxref("step", "input")}}</td>
  </tr>
  <tr>
   <td><strong>IDL 특성</strong></td>
   <td><code>list</code>, <code>value</code>, <code>valueAsDate</code>, <code>valueAsNumber</code>.</td>
  </tr>
  <tr>
   <td><strong>메서드</strong></td>
   <td>{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}</td>
  </tr>
 </tbody>
</table>

<h2 id="값"></h2>

<p>날짜 입력 칸의 값은 입력한 날짜를 나타내는 {{domxref("DOMString")}}입니다. 날짜는 유효한 날짜 문자열 문서에서 설명하듯, ISO8601을 따르는 서식을 취합니다.</p>

<p>{{htmlattrxref("value", "input")}} 특성에 날짜를 지정해서 입력 칸의 기본값을 지정할 수 있습니다.</p>

<pre class="brush: html">&lt;input type="date" value="2017-06-01"&gt;</pre>

<p>{{EmbedLiveSample('값', 600, 40)}}</p>

<div class="blockIndicator note">
<p><strong>표시 값과 실제 <code>value</code>의 불일치</strong> — 입력 칸에 표시되는 값은 사용자 브라우저의 로케일에 기반한 서식을 따라가지만, <code>value</code>는 항상 <code>yyyy-mm-dd</code>의 서식을 사용합니다.</p>
</div>

<p>입력 요소의 날짜 값은 JavaScript의 {{domxref("HTMLInputElement.value", "value")}}{{domxref("HTMLInputElement.valueAsNumber", "valueAsNumber")}} 속성으로 설정할 수도 있습니다. 다음 예제 코드를 보세요.</p>

<pre class="brush: js">var dateControl = document.querySelector('input[type="date"]');
dateControl.value = '2017-06-01';
console.log(dateControl.value); // prints "2017-06-01"
console.log(dateControl.valueAsNumber); // prints 1496275200000, a UNIX timestamp</pre>

<p>위의 코드는 <code>type</code><code>date</code>인 첫 번째 {{HTMLElement("input")}} 요소를 찾아서, 값을 <code>2017-06-01</code>로 설정합니다. 그리고 값을 다시 문자열과 숫자 형태로 가져옵니다.</p>

<h2 id="추가_특성">추가 특성</h2>

<p>모든 {{htmlelement("input")}} 요소의 공용 특성 외에도, <code>date</code> 유형은 아래의 특성도 지원합니다.</p>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">특성</th>
   <th scope="col">설명</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code>{{anch("max")}}</code></td>
   <td>허용하는 가장 늦은 날짜</td>
  </tr>
  <tr>
   <td><code>{{anch("min")}}</code></td>
   <td>허용하는 가장 이른 날짜</td>
  </tr>
  <tr>
   <td><code>{{anch("step")}}</code></td>
   <td>위/아래 조절 버튼을 눌렀을 때와, 날짜 유효성을 검증할 때 사용하는 스텝 간격.</td>
  </tr>
 </tbody>
</table>

<h3 id="htmlattrdefmax">{{htmlattrdef("max")}}</h3>

<p>받을 수 있는 제일 나중 날짜. 입력받은 {{htmlattrxref("value", "input")}}<code>max</code>보다 더 나중이라면 유효성 검증에 실패합니다. <code>max</code>의 값이 <code>yyyy-mm-dd</code> 형식의 유효한 날짜 문자열이 아니면 최댓값을 지정하지 않은 것으로 간주합니다.</p>

<p><code>max</code><code>min</code> 특성을 모두 사용할 경우, <code>max</code><code>min</code><strong>동일하거나 이후</strong>인 날짜 문자열이어야 합니다.</p>

<h3 id="htmlattrdefmin">{{htmlattrdef("min")}}</h3>

<p>받을 수 있는 제일 이전 날짜. 입력받은 {{htmlattrxref("value", "input")}}<code>min</code>보다 더 이전이라면 유효성 검증에 실패합니다. <code>min</code>의 값이 <code>yyyy-mm-dd</code> 형식의 유효한 날짜 문자열이 아니면 최솟값을 지정하지 않은 것으로 간주합니다.</p>

<p><code>max</code><code>min</code> 특성을 모두 사용할 경우, <code>min</code><code>max</code><strong>동일하거나 이전</strong>인 날짜 문자열이어야 합니다.</p>

<h3 id="htmlattrdefstep">{{htmlattrdef("step")}}</h3>

<p>{{page("/en-US/docs/Web/HTML/Element/input/number", "step-include")}}</p>

<p><code>date</code> 입력 칸의 <code>step</code> 값은 날짜 단위, 즉 밀리초 단위로 86,400,000 ✕ <code>step</code>로 처리합니다. 기본값은 1로, 하루를 나타냅니다.</p>

<div class="blockIndicator note">
<p><strong>참고:</strong> <code>date</code> 입력 칸에서 <code>step</code>의 값으로 <code>any</code>를 지정하면 <code>1</code>과 같습니다.</p>
</div>

<h2 id="날짜_입력_칸_사용하기">날짜 입력 칸 사용하기</h2>

<p>날짜 입력 칸은 꽤 편리하게 보입니다. 날짜를 선택할 수 있는 쉬운 인터페이스를 제공하고, 서버로 값을 전송할 땐 현재 사용자의 로케일과 관계 없이 정규화하니까요. 그러나, 지금은 제한적인 브라우저 지원으로 인한 문제가 존재합니다.</p>

<p>이 구획에서는 <code>&lt;input type="date"&gt;</code>의 기본 사용법과 복잡한 사용법을 살펴볼 것이고, 뒤에서는 브라우저 지원 문제를 처리할 때 사용할 수 있는 조언을 드리겠습니다. ({{anch("미지원 브라우저 처리하기")}}로 가세요.)</p>

<div class="blockIndicator note">
<p>모든 브라우저에서 날짜 입력 칸을 지원하는 날이 오면 이 문제도 자연스럽게 사라질 것입니다.</p>
</div>

<h3 id="기본_예제">기본 예제</h3>

<p><code>&lt;input type="date"&gt;</code>의 가장 간단한 사용법은 아래 코드처럼 하나의 <code>&lt;input&gt;</code>과 그 {{htmlelement("label")}}로 이뤄집니다.</p>

<pre class="brush: html">&lt;form action="https://example.com"&gt;
  &lt;label&gt;
    Enter your birthday:
    &lt;input type="date" name="bday"&gt;
  &lt;/label&gt;

  &lt;p&gt;&lt;button&gt;Submit&lt;/button&gt;&lt;/p&gt;
&lt;/form&gt;</pre>

<p>{{EmbedLiveSample('기본_예제', 600, 40)}}</p>

<p>위의 HTML은 입력받은 날짜를 <code>bday</code>라는 키로 <code>https://example.com</code>에 제출합니다. 그래서, 최종 URL은 <code>https://example.com/?bday=1955-06-08</code>이 됩니다.</p>

<h3 id="최대와_최소_날짜_설정">최대와 최소 날짜 설정</h3>

<p>{{htmlattrxref("min", "input")}}{{htmlattrxref("max", "input")}} 특성을 사용하면 사용자가 선택할 수 있는 날짜를 제한할 수 있습니다. 다음 코드에서는 최소 날짜 <code>2017-04-01</code>, 최대 날짜 <code>2017-04-30</code>을 지정합니다.</p>

<pre class="brush: html">&lt;form&gt;
  &lt;label for="party"&gt;Choose your preferred party date:
    &lt;input type="date" name="party" min="2017-04-01" max="2017-04-30"&gt;
  &lt;/label&gt;
&lt;/form&gt;</pre>

<p>{{EmbedLiveSample('최대와_최소_날짜_설정', 600, 40)}}</p>

<p>실행 결과에서 2017년 4월의 날짜만 선택 가능함을 볼 수 있습니다. 입력 칸의 연과 월은 편집이 불가능해지며, 날짜 선택 위젯에서도 2017년 4월 바깥의 날짜는 선택할 수 없습니다.</p>

<div class="note">
<p><strong>참고</strong>: 원래 {{htmlattrxref("step", "input")}} 특성을 사용해 날짜를 증감할 때 늘어날 일 수를 조절할 수 있어야 하고, 이를 이용해 토요일만 선택 가능하게 하는 등의 처리가 가능해야 합니다. 그러나 지금은 아무 브라우저에서도 구현하고 있지 않습니다.</p>
</div>

<h3 id="입력_칸_크기_조절">입력 칸 크기 조절</h3>

<p><code>&lt;input type="date"&gt;</code>{{htmlattrxref("size", "input")}} 등의 크기 조절 특성을 지원하지 않습니다. <a href="/ko/docs/Web/CSS">CSS</a>를 사용하세요.</p>

<h2 id="유효성_검사">유효성 검사</h2>

<p><code>&lt;input type="date"&gt;</code>는 기본값에선 값의 형식 외에 다른 유효성 검사는 수행하지 않습니다. 보통 날짜 입력 칸의 인터페이스가 날짜 이외의 값을 처음부터 허용하지 않는 것이 유용하긴 하나, 아무 값을 입력하지 않을 수도 있고, 미지원 브라우저에서 텍스트 입력 칸으로 대체된 경우 4월 32일처럼 유효하지 않은 날짜도 입력할 수 있습니다.</p>

<p>{{htmlattrxref("min", "input")}}{{htmlattrxref("max", "input")}}를 사용해 가능한 날짜 범위를 제한({{anch("최대와 최소 날짜 설정")}})한 경우, 지원하는 브라우저에서는 범위 밖의 값을 받았을 때 오류를 표시합니다. 그러나 브라우저가 온전히 지원하지 않을 수도 있기 때문에, 제출받은 값을 이중으로 검증하는 것이 필요합니다.</p>

<p>{{htmlattrxref("required", "input")}} 특성을 사용해 값을 필수로 요구할 수도 있으며, 빈 입력 칸을 제출하려고 하면 오류를 표시합니다. required는 대부분의 브라우저에서, 텍스트 입력 칸으로 대체되더라도 지원하고 있습니다.</p>

<p>최소/최대 날짜와 필수 검증 예제를 보겠습니다.</p>

<pre class="brush: html">&lt;form&gt;
  &lt;label&gt;
    Choose your preferred party date (required, April 1st to 20th):
    &lt;input type="date" name="party" min="2017-04-01" max="2017-04-20" required&gt;
    &lt;span class="validity"&gt;&lt;/span&gt;
  &lt;/label&gt;

  &lt;p&gt;
    &lt;button&gt;Submit&lt;/button&gt;
  &lt;/p&gt;
&lt;/form&gt;</pre>

<p>날짜 입력 칸의 입력을 완전히 끝내지 않았거나, 범위 밖의 값으로 제출을 시도하면 브라우저가 오류를 표시하는 것을 확인할 수 있습니다. 아래 실행 결과에서 직접 해보세요.</p>

<p>{{EmbedLiveSample('유효성_검사', 600, 100)}}</p>

<p>지원하지 않는 브라우저를 사용하시는 경우엔 다음 스크린샷을 참고하세요.</p>

<p><img alt="The input field has an overlaid speech balloon, with an orange exclamation mark icon and the message “Please fill in this field.”" src="https://mdn.mozillademos.org/files/14913/date-picker-chrome-error-message.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p>

<p>다음은 위 코드에서 사용한 CSS로, {{cssxref(":valid")}}{{cssxref(":invalid")}} 의사 클래스를 사용해 입력한 값의 유효성 여부에 따라 다른 스타일을 적용하고 있습니다. 구체적으로는, 유효성에 따라 입력 칸의 옆에 배치한 {{htmlelement("span")}}에 아이콘을 추가합니다.</p>

<pre class="brush: css">label {
  display: flex;
  align-items: center;
}

span::after {
  padding-left: 5px;
}

input:invalid + span::after {
  content: '✖';
}

input:valid+span::after {
  content: '✓';
}</pre>

<div class="warning">
<p><strong>중요</strong>: 클라이언트측 유효성 검사는 서버의 검사를 대체할 수 없습니다. HTML을 수정하는 것도 쉽지만, HTML을 완전히 우회하고 서버에 데이터를 직접 제출할 수도 있기 때문입니다. 서버가 받은 데이터의 검증을 하지 못하는 경우 잘못된 형식, 잘못된 유형, 너무 큰 데이터 등으로 인해 심각한 상황을 맞을 수도 있습니다.</p>
</div>

<h2 id="미지원_브라우저_처리하기">미지원 브라우저 처리하기</h2>

<p>위에서 언급했듯, 현재 날짜 입력 칸의 큰 문제는 {{anch("브라우저 호환성", "브라우저 지원")}}입니다. 예를 하나 들자면, Firefox for Android의 날짜 입력기는 다음과 같은 모습입니다.</p>

<p><img alt="A popup calendar picker modal floats above the web page and browser UI." src="https://mdn.mozillademos.org/files/14915/date-picker-fxa.png" style="display: block; margin: 0 auto;"></p>

<p>지원하지 않는 브라우저에서는 단순한 텍스트 입력 칸으로 우아하게 저하되긴 하지만, 이는 (보여지는 컨트롤이 다르므로) 사용자 인터페이스와 데이터 처리가 일관적이지 못하다는 문제를 만듭니다.</p>

<p>두 문제 중 데이터 처리가 더 심각합니다. 날짜 입력 칸을 지원하는 브라우저에서는 값을 <code>yyyy-mm-dd</code>의 형식으로 정규화합니다. 그러나 텍스트 입력만으로는 값의 형식을 브라우저가 알 수 없으며, 사람들은 다양한 형태로 날짜를 입력합니다. 다음은 그 일부입니다.</p>

<ul>
 <li><code>yymmdd</code></li>
 <li><code>yyyymmdd</code></li>
 <li><code>yyyy/mm/dd</code></li>
 <li><code>yyyy-mm-dd</code></li>
 <li><code>dd/mm/yyyy</code></li>
 <li><code>mm-dd-yyyy</code></li>
</ul>

<p>해결하는 방법 중 하나는 날짜 입력 칸에 {{htmlattrxref("pattern", "input")}} 특성을 사용하는 것입니다. 날짜 입력 칸은 사용하지 않는 특성이지만 텍스트 입력 칸으로 대체된 경우에는 사용하기 때문인데, 미지원 브라우저에서 다음 코드를 확인해보세요.</p>

<pre class="brush: html">&lt;form&gt;
  &lt;label for="bday"&gt;Enter your birthday:
    &lt;input type="date" name="bday" required pattern="\d{4}-\d{2}-\d{2}"&gt;
    &lt;span class="validity"&gt;&lt;/span&gt;
  &lt;/label&gt;
  &lt;p&gt;
    &lt;button&gt;Submit&lt;/button&gt;
  &lt;/p&gt;
&lt;/form&gt;</pre>

<p>{{EmbedLiveSample('미지원_브라우저_처리하기', 600, 100)}}</p>

<p>입력한 값을 패턴 <code>####-##-##</code> (<code>#</code>은 0에서 9까지의 숫자)에 맞추지 않고 제출해보면 브라우저가 날짜 입력 칸을 강조하며 오류를 표시함을 볼 수 있습니다. 물론 아직도 사람들이 유효하지 않은 날짜나 잘못된 형태로 입력하는 것은 막을 수 없으므로, 문제를 해결한 것은 아닙니다.</p>

<div class="hidden">
<pre class="brush: css">span {
  position: relative;
}

span::after {
  right: -18px;
  position: absolute;
}

input:invalid + span::after {
  content: '✖';
}

input:valid + span::after {
  content: '✓';
}</pre>
</div>

<p>그러므로 지금으로서는, 크로스 브라우저 날짜 처리를 지원하기 위한 가장 좋은 방법은 각각 다른 입력 칸에 연, 월, 일을 입력하도록 하는 방법과, 외부 JavaScript 라이브러리를 사용하는 편이 최선입니다.</p>

<h2 id="예제">예제</h2>

<p>이번 예제에서는 날짜를 선택할 수 있는 사용자 인터페이스 두 개를 만들어보겠습니다. 첫 번째는 네이티브 <code>&lt;input type="date"&gt;</code> 입력 칸을 사용한 것이고, 두 번째는 네이티브 입력 칸을 지원하지 않는 구형 브라우저에서 사용할 수 있도록 세 개의 {{htmlelement("select")}} 요소를 이용한 것입니다.</p>

<p>{{EmbedLiveSample('예제', 600, 100)}}</p>

<h3 id="HTML">HTML</h3>

<p>HTML은 다음과 같습니다.</p>

<pre class="brush: html">&lt;form&gt;
  &lt;label class="nativeDatePicker"&gt;Enter your birthday:
    &lt;input type="date" name="bday"&gt;
    &lt;span class="validity"&gt;&lt;/span&gt;
  &lt;/label&gt;

  &lt;fieldset class="fallbackDatePicker" hidden&gt;
    &lt;legend class="fallbackLabel"&gt;Enter your birthday:&lt;/legend&gt;

    &lt;label&gt;
      Day:
      &lt;select name="day"&gt;&lt;/select&gt;
    &lt;/label&gt;

    &lt;label&gt;
      Month:
      &lt;select name="month"&gt;
        &lt;option&gt;January&lt;/option&gt;
        &lt;option&gt;February&lt;/option&gt;
        &lt;option&gt;March&lt;/option&gt;
        &lt;option&gt;April&lt;/option&gt;
        &lt;option&gt;May&lt;/option&gt;
        &lt;option&gt;June&lt;/option&gt;
        &lt;option&gt;July&lt;/option&gt;
        &lt;option&gt;August&lt;/option&gt;
        &lt;option&gt;September&lt;/option&gt;
        &lt;option&gt;October&lt;/option&gt;
        &lt;option&gt;November&lt;/option&gt;
        &lt;option&gt;December&lt;/option&gt;
      &lt;/select&gt;
    &lt;/label&gt;

    &lt;label&gt;
      Year:
      &lt;select name="year"&gt;&lt;/select&gt;
    &lt;/label&gt;
  &lt;/fieldset&gt;
&lt;/form&gt;</pre>

<p>월은 변하지 않으므로 하드코딩합니다. 일과 연은 현재 선택 값에 따라 동적으로 생성하도록 비워놓습니다. (자세한 설명은 아래의 코드 주석을 참고하세요.)</p>

<div class="hidden">
<pre class="brush: css">span {
  padding-left: 5px;
}

input:invalid + span::after {
  content: '✖';
}

input:valid + span::after {
  content: '✓';
}</pre>
</div>

<h3 id="JavaScript">JavaScript</h3>

<p>코드에서 관심을 가질만한 곳은 브라우저의 <code>&lt;input type="date"&gt;</code> 지원 여부를 알아내기 위한 기능 탐지 부분입니다.</p>

<p>우선 새로운 {{htmlelement("input")}} 요소를 만들고, <code>type</code><code>date</code>로 설정해봅니다. 그리고 즉시 <code>&lt;input&gt;</code>의 유형을 검사하는데, 지원하지 않는 브라우저에서 <code>date</code><code>text</code>로 대체되므로 <code>text</code>를 반환합니다. <code>&lt;input type="date"&gt;</code>을 지원하지 않는다는 사실을 알아냈으면 네이티브 입력 칸을 숨기고, 대체 요소({{htmlelement("select")}})를 대신 노출합니다.</p>

<pre class="brush: js">// define variables
var nativePicker = document.querySelector('.nativeDatePicker');
var fallbackPicker = document.querySelector('.fallbackDatePicker');

var yearSelect = document.querySelector('[name=year]');
var monthSelect = document.querySelector('[name=month]');

// Test whether a new date input falls back to a text input
var testElement = document.createElement('input');

try {
  test.type = 'date';
} catch (e) {
  console.log(e.description);
}

// If it does, run the code inside the if () {} block
if (testElement.type === 'text') {
  // hide the native picker and show the fallback
  nativePicker.hidden = true;
  fallbackPicker.hidden = false;

  // populate the days and years dynamically
  // (the months are always the same, therefore hardcoded)
  populateDays(monthSelect.value);
  populateYears();
}

function populateDays(month) {
  const daySelect = document.querySelector('[name=day]');
  const month = monthSelect.value;

  // Create variable to hold new number of days to inject
  let dayNum;

  // 31 or 30 days?
  switch (month) {
    case 'April': case 'June': case 'September': case 'November':
      dayNum = 30;
    break;
    case 'February':
      // If month is February, calculate whether it is a leap year or not
      const year = yearSelect.value;
      const isLeap = new Date(year, 1, 29).getMonth() === 1;
      dayNum = isLeap ? 29 : 28;
    break;
    default:
      dayNum = 31;
  }

  // inject the right number of new &lt;option&gt;s into the &lt;select&gt;
  daySelect.options = Array.from({ length: dayNum }, function(index) {
    return index + 1;
  });

  // if previous day has already been set, set daySelect's value
  // to that day, to avoid the day jumping back to 1 when you
  // change the year
  if (previousDay) {
    daySelect.value = previousDay;

    // If the previous day was set to a high number, say 31, and then
    // you chose a month with fewer days in it (like February),
    // this code ensures that the highest day available
    // is selected, rather than showing a blank daySelect
    if (previousDay &gt; daySelect.length + 1) {
      daySelect.selectedIndex = daySelect.length;
    }
  }
}

function populateYears() {
  // get this year as a number
  var year = (new Date()).getFullYear();

  // Make this year and the 100 years before it available in the &lt;select&gt;
  daySelect.options = Array.from({ length: 100 }, function(index) {
    return index + year;
  });
}

// when the month or year &lt;select&gt; values are changed, rerun populateDays()
// in case the change affected the number of available days
yearSelect.onchange = populateDays;
monthSelect.onchange = populateDays;

// preserve day selection
var previousDay;

// update what day has been set to previously
// see end of populateDays() for usage
daySelect.onchange = function() {
  previousDay = daySelect.value;
}</pre>

<div class="note">
<p><strong>참고</strong>: 어떤 연도는 53주임을 기억하세요! (<a href="https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year">Wikipedia</a>) 프로덕션 애플리케이션을 개발할 땐 고려해야 할 사항입니다.</p>
</div>

<h2 id="명세">명세</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comments</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('HTML WHATWG', 'forms.html#date-state-(type=date)', '&lt;input type="date"&gt;')}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('HTML5 W3C', 'forms.html#date-state-(type=date)', '&lt;input type="date"&gt;')}}</td>
   <td>{{Spec2('HTML5 W3C')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="브라우저_호환성">브라우저 호환성</h2>

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

<p>{{Compat("html.elements.input.input-date")}}</p>

<h2 id="같이_보기">같이 보기</h2>

<ul>
 <li>일반 {{HTMLElement("input")}} 요소와, 그 인터페이스인 {{domxref("HTMLInputElement")}}.</li>
</ul>