Recipe 11.1

Formatting a Date

Select a date and a format type to see the formatted date. The example also shows the results of the formatToParts method.

Demo

Results

Formatted date

Formatted date parts


Code

JavaScript
const dateForm = document.querySelector('#date-form');
const output = document.querySelector('#output');

dateForm.addEventListener('submit', event => {
  event.preventDefault();

  const format = new Intl.DateTimeFormat(navigator.language, { dateStyle: dateForm.elements.format.value });

  output.querySelector('#formatted-date').textContent = format.format(dateForm.elements.date.valueAsDate);
  output.querySelector('#parts').textContent = JSON.stringify(format.formatToParts(dateForm.elements.date.valueAsDate), null, 2);
  output.classList.remove('d-none');
});
HTML
<form id="date-form">
  <div class="my-4">
    <label class="form-label" for="date">Date</label>
    <input required id="date" type="date" class="form-control" name="date">
  </div>

  <div class="my-4">
    <label class="form-label" for="format">Format</label>
    <select required class="form-select" name="format">
      <option>short</option>
      <option>medium</option>
      <option>long</option>
      <option>full</option>
    </select>
  </div>

  <button type="submit" class="btn btn-primary">Format Date</button>
</form>

<div id="output" class="d-none my-4">
  <h2>Results</h2>
  <h3>Formatted date</h3>
  <div id="formatted-date"></div>
  <h3>Formatted date parts</h3>
  <pre id="parts"></pre>
</div>
Web API Cookbook
Joe Attardi