简体   繁体   中英

How to change date format to dd/mm/yyyy in html input

I want to change the date format mm/dd/yyyy to dd/mm/yyyy in the input field.

My input field :

<input type="date">

You will need to add some javascript to the code, please read the following comment

https://stackoverflow.com/a/31162426/6353996

There is no native way of doing that, but here is my HTML + JS solution:

 <script> function DDMMYYYY(value, event) { let newValue = value.replace(/[^0-9]/g, '').replace(/(\\..*)\\./g, '$1'); const dayOrMonth = (index) => index % 2 === 1 && index < 4; // on delete key. if (!event.data) { return value; } return newValue.split('').map((v, i) => dayOrMonth(i) ? v + '/' : v).join('');; } </script> <input type="tel" maxlength="10" placeholder="dd/mm/yyyy" oninput="this.value = DDMMYYYY(this.value, event)" />

  • It uses the native HTML "oninput" method so the user don't see anything blinking.
  • Using "type=tel" it opens a number keyboard on any mobile device.
  • Basically it's adding '/' after the day and the month and deleting everything else.

Hope it will help someone in the future :)

There is no way to change the default date type input except using CSS and js

 $("input").on("change", function() { this.setAttribute( "data-date", moment(this.value, "YYYY-MM-DD") .format( this.getAttribute("data-date-format") ) ) }).trigger("change")
 input { position: relative; width: 150px; height: 20px; color: white; } input:before { position: absolute; top: 3px; left: 3px; content: attr(data-date); display: inline-block; color: black; } input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button { display: none; } input::-webkit-calendar-picker-indicator { position: absolute; top: 3px; right: 0; color: black; opacity: 1; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> <input type="date" data-date="" data-date-format="DD/MM/YYYY" value="2020-08-29">

\n
\n
\n
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
\n
\n
\n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM