Input type date, how to format output

Asked

Viewed 2,633 times

2

Is there any way, using only HTML attributes to format a <input> to receive date formatted for ano/mês/dia?

If it does not exist in HTML there is some way to do this via Javascript when selecting the date without using the event onblur?

  • 1

    The question is not very clear to me? can explain better and add an example of what you want?

  • Friend, I’ll tex explain better, when I put input type="date" in html it shows the datepicker for me right? only that the date format when you click on some dd/mm/yyyy date, I wanted to change it to yyyy/mm/dd

  • Ok, and when you need the value? has some form-Ubmit or you will fetch the value with javascript?

  • 1

    Please edit your question so everyone understands better. Edited, it gets more complete and the chances of getting a good answer increase

  • I have already explained how to give, I want to format a date field in HTML with a different output of dd/mm/yyyy, it will be submitted and saved through a form

  • 1

    So now, edit the question with the new information you put in the comments. Not everyone reads comments.

  • @Alexander, have you ever used javascript datepicker? It’s magical.

Show 2 more comments

2 answers

2

Use the Plugin jqMask

To use it just include the file jqmask.js on your page and then use it as follows:

$('#ID_Do_Seu_Input').('99/99/9999');

2


Different browsers show the date in different ways. Chrome for example uses your country/location format to format the date. However, apart from this visual difference, the date that is sent is the same. So if you want to ensure that you have the format you want then I suggest using Javascript.

If you have a form that needs to be sent, I suggest you create a input type="hidden" hidden that gets the datepicker value in the format you want.

Suggestion:

HTML

<form action="">
    <input type="date" />
    <input id="formatedDate" type="hidden" />
</form>

Javascript / jQuery

function convertDate(inputFormat) {
    function pad(s) {
        return (s < 10) ? '0' + s : s;
    }
    var d = new Date(inputFormat);
    return [
        pad(d.getFullYear()), 
        pad(d.getMonth() + 1), 
        d.getDate()
    ].join('/');
}
$('input').on('change', function () {
    $('#formatedDate').val(convertDate(this.value));
});

Note that not all browsers support input type="date" / HTML5. If you are using another datepicker then you can use the function above. If datepicker uses timestamp Unix (server-side commum), then it should use convertDate(this.value * 1000)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.