Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

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

My input field :

<input type="date">
like image 665
Mehedi Hasan Siam Avatar asked Sep 01 '18 10:09

Mehedi Hasan Siam


2 Answers

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 :)

like image 179
Daniel Liverant Avatar answered Sep 19 '22 15:09

Daniel Liverant


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">
like image 40
Mehedi Hasan Siam Avatar answered Sep 18 '22 15:09

Mehedi Hasan Siam