<input type="date">

This translation is in progress.

date 유형의 <input> 요소는 유효성 검증을 포함하는 텍스트 상자 또는 특별한 날짜 선택 인터페이스를 사용해 날짜를 입력할 수 있는 입력 칸을 생성합니다.

입력 칸의 값은 연, 월, 일을 포함하지만 시간은 포함하지 않습니다. timedatetime-local 입력 유형이 시간과 시간 + 날짜 조합을 지원합니다.

입력 UI는 브라우저마다 다릅니다. 브라우저 호환성에서 더 자세한 정보를 알아보세요. 날짜 입력 유형을 지원하지 않는 브라우저에서는 우아하게 <input type="text">로 저하됩니다.

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

A textbox containing “dd/mm/yyyy”, an increment/decrement button combo, and a downward arrow that opens into a calendar control.

구 Edge의 컨트롤입니다.

A textbox containing “mm/dd/yyyy”, but when interacted with, opens a tri-column date selector.

Firefox의 날짜 컨트롤입니다.

Another “dd/mm/yyyy” textbox that expands into a selectable calendar control.

YYYY-MM-DD 형식으로 날짜를 나타내거나, 빈 DOMString.
이벤트 change, input
지원하는 공통 특성 autocomplete, list, readonly, step
IDL 특성 list, value, valueAsDate, valueAsNumber.
메서드 select(), stepDown(), stepUp()

날짜 입력 칸의 값은 입력한 날짜를 나타내는 DOMString입니다. 날짜는 유효한 날짜 문자열 문서에서 설명하듯, ISO8601을 따르는 서식을 취합니다.

value 특성에 날짜를 지정해서 입력 칸의 기본값을 지정할 수 있습니다.

<input type="date" value="2017-06-01">

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

입력 요소의 날짜 값은 JavaScript의 valuevalueAsNumber 속성으로 설정할 수도 있습니다. 다음 예제 코드를 보세요.

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

위의 코드는 typedate인 첫 번째 <input> 요소를 찾아서, 값을 2017-06-01로 설정합니다. 그 후에 값을 다시 문자열과 숫자 형태로 가져옵니다.

추가 특성

모든 <input> 요소의 공용 특성 외에도, date 유형은 아래의 특성도 지원합니다.

특성 설명
max 허용하는 가장 늦은 날짜
min 허용하는 가장 이른 날짜
step 위/아래 조절 버튼을 눌렀을 때와, 날짜 유효성을 검증할 때 사용하는 스텝 간격.

max

The latest date to accept. If the value entered into the element occurs afterward, the element fails constraint validation. If the value of the max attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no maximum date value.

If both the max and min attributes are set, this value must be a date string later than or equal to the one in the min attribute.

min

The earliest date to accept. If the value entered into the element occurs beforehand, the element fails constraint validation. If the value of the min attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no minimum date value.

If both the max and min attributes are set, this value must be a date string earlier than or equal to the one in the max attribute.

step

The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid.

A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max).

Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.

Number of days to increment at a time. Each day is treated as a number of milliseconds equal to 86,400,000✕step. The default value is 1, for one day.

Specifying "any" as the value for step has the same effect as 1 for date inputs.

날짜 입력 칸 사용하기

Date inputs sound convenient — they provide an easy interface for choosing dates, and they normalize the data format sent to the server regardless of the user's locale. However, there are currently issues with <input type="date"> because of its limited browser support.

In this section, we'll look at basic and then more complex uses of <input type="date">, and offer advice on mitigating the browser support issue later (see Handling browser support).

Hopefully, over time browser support will become ubiquitous, and this problem will fade away.

기본 예제

The simplest use of <input type="date"> involves one <input> combined with its <label>, as seen below:

<form action="https://example.com">
  <label>
    Enter your birthday:
    <input type="date" name="bday">
  </label>

  <p><button>Submit</button></p>
</form>

This HTML submits the entered date under the key bday to https://example.com — resulting in a URL like https://example.com/?bday=1955-06-08.

최대와 최소 날짜 설정

You can use the min and max attributes to restrict the dates that can be chosen by the user. In the following example, we sett a minimum date of 2017-04-01 and a maximum date of 2017-04-30:

<form>
  <label for="party">Choose your preferred party date:
    <input type="date" name="party" min="2017-04-01" max="2017-04-30">
  </label>
</form>

The result is that only days in April 2017 can be selected — the month and year parts of the textbox will be uneditable, and dates outside April 2017 can't be selected in tte picker widget.

Note: You should be able to use the step attribute to vary the number of days jumped each time the date is incremented (e.g. to only make Saturdays selectable). However, this does not seem to be in any implementation at the time of writing.

입력 칸 크기 조절

<input type="date"> doesn't support form sizing attributes such as size. Prefer CSS for sizing it.

유효성 검사

By default, <input type="date"> doesn't validate the entered value beyond its format. The interfaces generally don't let you enter anything that isn't a date — which is helpful — but you can leave the field empty or enter an invalid date in browsers where the input falls back to type text (like the 32nd of April).

If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is out of bounds. However, you'll need to double-check the submitted results to ensure the value is within these dates, if the date picker isn't fully supported on the user's device.

You can also use the required attribute to make filling in the date mandatory — an error will be displayed if you try to submit an empty date field. This should work in most browsers, even if they fall back to a text input.

Let's look at an example of minimum and maximum dates, and also made a field:

<form>
  <label>
    Choose your preferred party date (required, April 1st to 20th):
    <input type="date" name="party" min="2017-04-01" max="2017-04-20" required>
    <span class="validity"></span>
  </label>
    
  <p>
    <button>Submit</button>
  </p>
</form>

If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:

Here's a screenshot for those of you who aren't using a supporting browser:

The input field has an overlaid speech balloon, with an orange exclamation mark icon and the message “Please fill in this field.”

Here's the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a <span> next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively.

label {
  display: flex;
  align-items: center;
}

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

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

input:valid+span::after {
  content: '✓';
}

Important: Client-side form validation is no substitute for validating on the server. It's easy for someone to modify the HTML, or bypass your HTML entirely and submit the data directly to your server. If your server fails to validate the received data, disaster could strike with data that is badly-formatted, too large, of the wrong type, etc.

미지원 브라우저 처리하기

As mentioned, the major problem with date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:

A popup calendar picker modal floats above the web page and browser UI.

Unsupporting browsers gracefully degrade to a text input, but this creates problems in consistency of user interface (the presented controls are different) and data handling.

The second problem is the more serious one; with date input supported, the value is normalized to the format yyyy-mm-dd. But with a text input, the browser has no recognition of what format the date should be in, and there are many different formats in which people write dates. For example:

  • ddmmyyyy
  • dd/mm/yyyy
  • mm/dd/yyyy
  • dd-mm-yyyy
  • mm-dd-yyyy
  • Month dd, yyyy

One way around this is the pattern attribute on your date input. Even though the date picker doesn't use it, the text input fallback will. For example, try viewing the following in a unsupporting browser:

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

If you submit it, you'll see that the browser displays an error and highlights the input as invalid if your entry doesn't match the pattern ####-##-## (where # is a digit from 0 to 9). Of course, this doesn't stop people from entering invalid dates, or incorrect formats. So we still have a problem.

At the moment, the best way to deal with dates in forms in a cross-browser way is to have the user enter the day, month, and year in separate controls, or to use a JavaScript library such as jQuery date picker.

예제

In this example, we create 2 sets of UI elements for choosing dates: a native <input type="date"> picker and a set of 3 <select> elements for older browsers that don't support the native date input.

HTML

The HTML looks like so:

<form>
  <label class="nativeDatePicker">Enter your birthday:
    <input type="date" name="bday">
    <span class="validity"></span>
  </label>

  <fieldset class="fallbackDatePicker" hidden>
    <legend class="fallbackLabel">Enter your birthday:</legend>

    <label>
      Day:
      <select name="day"></select>
    </label>

    <label>
      Month:
      <select name="month">
        <option>January</option>
        <option>February</option>
        <option>March</option>
        <option>April</option>
        <option>May</option>
        <option>June</option>
        <option>July</option>
        <option>August</option>
        <option>September</option>
        <option>October</option>
        <option>November</option>
        <option>December</option>
      </select>
    </label>

    <label>
      Year:
      <select name="year"></select>
    </label>
  </fieldset>
</form>

The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)

JavaScript

The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="date">.

We create a new <input> element, try setting its type to date, then immediately check what its type is — unsupporting browsers will return text, because the date type falls back to type text. If <input type="date"> isn't supported, we hide the native picker and show the fallback (<select>) instead.

// 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 <option>s into the <select>
  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 > 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 <select>
  daySelect.options = Array.from({ length: 100 }, function(index) {
    return index + year;
  });
}

// when the month or year <select> 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;
}

Note: Remember that some years have 53 weeks in them (see Weeks per year)! You'll need to take this into consideration when developing production apps.

명세

Specification Status Comments
HTML Living Standard
The definition of '<input type="date">' in that specification.
Living Standard
HTML5
The definition of '<input type="date">' in that specification.
Recommendation

브라우저 호환성

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
type="date"Chrome Full support 20Edge Full support 12Firefox Full support 57IE No support NoOpera Full support 11Safari No support No
Notes
No support No
Notes
Notes The input type is recognized, but there is no date-specific control. See bug 119175.
WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 57Opera Android Full support 11Safari iOS Full support 5Samsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.

같이 보기