jQuery function to format date by . class

Asked

Viewed 2,447 times

1

I’m trying to make a script that gets the class . input date and convert the date to en, but I can’t do it, I’d like a help.

$.fn.converteData = function(){
    var data  = ($(this).val()).split("-");     
    var dataf = data[2]+data[1]+data[0];    
    $(this).val(dataf); 
    $(this).mask("99/99/9999"); //estou usando o plugin maskedinput
}

$(".data").converteData();


<form>
<label for="dt_nasc">Data de nascimento</label>
<input class="data" name="dt_nasc" type="text" value="1966-11-27">
</form>

I wish it was already automatically called for all html inputs with the . data class I get it in 1966-11-27 this script would be to convert 27/11/1966.

  • Can you put the HTML you have? what format these dates are in and what is the final format you want? (give examples)

  • Here is working normally.

  • Sergio, I added in the question.

1 answer

2

If I understand your question this is to change the date formatting:

$('input.data').each(function () {
    var data = new Date(this.value);
    this.value = [data.getDate(), data.getMonth() + 1, data.getFullYear()].join('/');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <label for="dt_nasc">Data de nascimento</label>
    <input class="data" name="dt_nasc" type="text" value="1966-11-27" />
</form>

In the code I first convert the date into a date object and then give the final format using native methods to fetch the day, year and month.

Another solution, without parsing the date:

$('input.data').each(function () {
    this.value = this.value.split('-').reverse().join('/');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <label for="dt_nasc">Data de nascimento</label>
    <input class="data" name="dt_nasc" type="text" value="1966-11-27" />
    <label for="dt_emissao">Data de emissão</label>
    <input class="data" name="dt_nasc" type="text" value="2005-08-25" />
</form>

  • I ran the sent code, it worked, but when I have more than one date on the form, the second one goes wrong. <form> <label for="dt_nasc">Date of birth</label> <input class="date" name="dt_nasc" type="text" value="1966-11-27" /> <label for="dt_emitted">Date of issue</label> <input class="date" name="dt_nasc type" ="text" value="2005-08-25" /> </form> the second date is 24/8/2005

  • @Exact jrjs. Isn’t that what you wanted? Date formatted dd/mm/aaaa? As here: http://jsfiddle.net/7e3trkgn/

  • @Jrjs ah, ok I’ve noticed, time zone problem maybe. I’ll add another solution without parsing the date...

  • @Jrjs added another version to the reply. Asssim: http://jsfiddle.net/7e3trkgn/1/

  • worked perfectly that last, thank you very much.

  • @Jrjs great. If you want you can mark the answer as accepted.

Show 1 more comment

Browser other questions tagged

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