9

I have a classic HTML date input: <input type="date" name="dto" id="date_timepicker_end">

enter image description here

Now I need to change this format to be dd/mm/yyyy, and I know I can't change that in html.

When I add the jQuery datepicker I just get a blank input form where you can type any number you want:

enter image description here

I need the input to be just like the HTML input, where the user clicks on the input and can just change the value according to what he clicked. I don't want him to be able to write any random number.

Also note, this is all custom code in a wordpress theme, so I have jquery and my custom javascript and css. I can't add libraries like moment.js and so on...

What is the best solution for this problem ? I know it has been asked a lot of times, but none of those methods work me for because I need the input field to be like a normal HTML input date field, not an empty input, dd/mm/yyyy instead if mm/dd/yyyy.

jsfiddle: https://jsfiddle.net/t4zrrvgL/

Ken Ratanachai S.
  • 3,307
  • 34
  • 43
IkePr
  • 900
  • 4
  • 18
  • 44

6 Answers6

6

As you already know, you can't change the value format in an input type="date".

The input type="date" uses a localized displaying format,
but its value is formatted like this: “YYYY-MM-DD”.
(Doc: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date)

Instead of trying to modify or use a pattern on the input of the datepicker,
I tried to use the regular input type="date" to work with the datepicker.

The datepicker has got a dateFormat option.
It seems that “yy-mm-dd” matches the format required by the input type="date".
Using that, I ended-up with a localized datepicker in an easy way:

// Use datepicker on the date inputs
$("input[type=date]").datepicker({
  dateFormat: 'yy-mm-dd',
  onSelect: function(dateText, inst) {
    $(inst).val(dateText); // Write the value in the input
  }
});

// Code below to avoid the classic date-picker
$("input[type=date]").on('click', function() {
  return false;
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input type="date">

Hope it helps.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47
3

Add readonly attribute to your html tag. This is restrict the user to enter the input.

<input type="text" name="dto" id="date_timepicker_end" readonly>

As you're using jQuery datepicker, it has option availble to specify the date format that you want to have.

 $("#date_timepicker_end").datepicker()
 {
    "dateFormat" : "dd-mm-yyyy" //any valid format that you want to have
 });

Hope this helps!!

Kgn-web
  • 7,047
  • 24
  • 95
  • 161
1

Its seems like I am a bit late to the party, but I faced similar issue recently. In my case I was getting the date in the yyyyy-mm-dd format, while I wanted it to be in dd/mm/yyyy format. So, I used JS array method split. Then in a new variable I made the format I need.

let dateWeGet='2000-11-21'

let changeFormat=()=>{
let dateArray=dateWeGet.split('-')

let newFormat=`${dateArray[1]}/${dateArray[2]}/${dateArray[0]}`
// mm/dd/yyyy

let newFormat2=`${dateArray[2]}/${dateArray[1]}/${dateArray[0]}`
//  dd/mm/yyyy

let newFormat3=`${dateArray[1]}-${dateArray[2]}-${dateArray[0]}`
//  dd-mm-yyyy

console.log(newFormat)
console.log(newFormat2)
console.log(newFormat3)
}


changeFormat()

Note, I don't know how to add snippets accurately, cause it's my first time answering a question. That's why I have written a JS snippet in which I am taking a hypothetical date. Meanwhile we can use States in ReactJS or document.getElementById() in vanilla JS to get the real date value. But the function will stay like this.

Now using this function, we can create whatever format we want.

0

you can change the date tag to:

<input type="date" id="myDate" max="2222-05-26">

This won't allow the users to enter more than 4 chars on year field. Also it doesn't really matter what they enter though, you can always perform Client-server side validations.

RavianXReaver
  • 96
  • 2
  • 9
0

I have come up with a method of using a text box to simulate the date input and do any format you want, here is the code

<html>
<body>
date : 
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
    <input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">&#9660;</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
    window.onload =function(){
        var input = document.createElement('input');
        input.setAttribute('type','date');
        input.setAttribute('value', 'some text'); 
        if(input.value === "some text"){
            allDates = document.getElementsByClassName("xDateContainer");
            matchEnterdDate=1;
            for (var i = 0; i < allDates.length; i++) {
                allDates[i].style.opacity = "1";
            } 
        }
    }
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
    var date = new Date(xObj.value);
    var month = date.getMonth();
    var day = date.getDate();
    var year = date.getFullYear();
    if(month!='NaN'){
        document.getElementById(xTraget).value=day+" / "+month+" / "+year;
    }else{
        if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
    }
}
   </script>
  </body>
</html>

1- please note that this method only work for browser that support date type.

2- the first function in JS code is for browser that don't support date type and set the look to a normal text input.

3- if you will use this code for multiple date inputs in your page please change the ID "xTime" of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.

4-on the second function you can use any format you want instead of day+" / "+month+" / "+year for example year+" / "+month+" / "+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.

shady
  • 9
  • 2
0

I have created a function with return type and passing date value to get my desired date format

      var date_picker_end = document.getElementById("date_picker_end").value;
      console.log("Date is:" + changedateformat(date_picker_end));



    function changedateformat(val) {
        const myArray = val.split("-");

        let year = myArray[0];
        let month = myArray[1];
        let day = myArray[2];

        let formatteddate = day + "-" + month + "-" + year; 
        return formatteddate;
    }
Praveen Kumar
  • 101
  • 1
  • 5