javascript – Different format for viewing and returning (bootstrap-datepicker)

Question:

I have the following calendar:

Início do período:
<input type="text" id="calendarioIni" name="dataInicio">

$(document).ready(function() 
{
    var dataIni = document.querySelector("#calendarioIni");
    var dataFim = document.querySelector("#calendarioFim");

    function checaVazio(){
        var botao = $("#consultar");
        var display = dataIni.val() && dataFim.val() ? "inline" : "none";
        $(botao).css("display",display);
  }

    $('#calendarioIni').datepicker({
        startDate: '01/01/1998', 
        endDate: '31/12/1998', 
        onSelect: checaVazio
    });

    $('#calendarioFim').datepicker({
        startDate: '01/01/1998',
        endDate: '31/12/1998', 
        onSelect: checaVazio
    });


});

I would like the user to appear in the format dd/mm/yyyy but return in the format yyyy/mm/dd or even yyyy-mm-dd , how could I perform this procedure?

Answer:

You can convert the date of each field to yyyy-mm-dd format directly in PHP when receiving via $_POST using strtotime() .

$dataIni = $_POST['dataInicio'];
$dataIni = str_replace('/','-',$dataIni);
$dataIni = date('Y-m-d', strtotime($dataIni));

$dataFim = $_POST['dataFim'];
$dataFim = str_replace('/','-',$dataFim);
$dataFim = date('Y-m-d', strtotime($dataFim));

Note that before converting you need to convert the slashes / into a hyphen - because strtotime() doesn't work correctly with / . ( See documentation )

Scroll to Top
AllEscort