Input type date, how to format output

2

Is there anyway, using only HTML attributes to format a <input> to receive data formatted to ano/mês/dia ?

If it does not exist in HTML is there any way to do this via Javascript at the time of date selection without using the onblur event?

    
asked by anonymous 06.02.2014 / 18:26

2 answers

2

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

If you have a form that has to be submitted, I suggest creating a hidden input type="hidden" fault 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 at the top. If the datepicker uses timestamp unix (server-side common), in this case you should use convertDate(this.value * 1000)

    
06.02.2014 / 18:50
2

Use the jqMask plugin

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

$('#ID_Do_Seu_Input').('99/99/9999');
    
06.02.2014 / 18:32