Change time and end date according to the initial

1

Each time you select a start time for the event in Google Calendar, it adds a 1 to the end time. Home For example: If you put 12:00 on 03/25 at the start, the final will appear at 13:00 on 03/25. However, when you put 23:00 on 03/06 on the initial, it changes the final to 00:00 04/06.

I would like to know the best way to do this in Javascript / Jquery.

    
asked by anonymous 25.05.2015 / 03:38

2 answers

1

One solution is to convert the string value of the initial datetime textboxes to a Date object of Javascript only and add a time to the value of it. After that, just convert it back to two strings and put the value in the final date and time textboxes. I made a snippet, take a look.

function calculaDataHoraFinal() {
  var valorDataIni = $("#data-ini").val();
  var valorHoraIni = $("#hora-ini").val();

  if (valorDataIni && valorHoraIni) {

    var partesData = valorDataIni.split("/");
    var partesHora = valorHoraIni.split(":");

    var dataIni = new Date(partesData[2], partesData[1] - 1, partesData[0], partesHora[0], partesHora[1]);
    var dataFim = new Date(dataIni.getTime());
    dataFim.setHours(dataFim.getHours() + 1);

    var partesHoraFim = dataFim.toTimeString().split(':');
    $("#data-fim").val(dataFim.toLocaleDateString());
    $("#hora-fim").val(partesHoraFim[0] + ':' + partesHoraFim[1]);

  }
}

$("#data-ini, #hora-ini").on('change', calculaDataHoraFinal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><inputid="data-ini" type="text" />
  <input id="hora-ini" type="text" />&nbsp;até&nbsp;
  <input id="data-fim" type="text" />
  <input id="hora-fim" type="text" />
</div>

I know there are date and format parsing methods, but they all depend on the location of the browser, and the culture definition for those methods is not well implemented in all browsers. If you want to make things simpler, you can use a date processing library for Javascript like Moment.js .

    
25.05.2015 / 04:27
1

var entrada = document.getElementById("txt-entrada");
var saida = document.getElementById("txt-saida");

function adicionarHora() {
    // converte string em data
    var data_entrada = moment(entrada.value, "DD/MM/YYYY HH:mm:ss");

    // define o valor da saida
    saida.value = moment(data_entrada).add(2, 'hour').format('DD/MM/YYYY HH:mm:ss');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<input type="text" id="txt-entrada" onkeyup="adicionarHora()" value="24/05/2015 23:00:00" placeholder="Entrada" />
<input type="text" id="txt-saida" placeholder="Saida" />

Use the MomentJS library. And using the add () method, you can add certain dates to the date:

See example working in JSFiddle ;

    
25.05.2015 / 04:23