Problem with control of type DATETIME-LOCAL of HTML5 returns me the hour ahead

0

I have this control

<div class="col-lg-6">
   <input type="datetime-local" name="fechahora" step="1" min="{{meta.fechaActual}}" ng-model="evento.fechaInicio">
</div>

But when I try it and select for example the next hour 01/02/2017 12:23:22 the angle model loads me the following

{"fechaInicio":"2017-03-02T16:22:23.000Z"}

Apparently, the value returns 4 hours ahead. Why does it happen?

    
asked by Anthony Medina 28.02.2017 в 18:06
source

2 answers

2

We go in parts:

  • 2017-03-02T16:22:23.000Z After the day, where the letter "T" begins T00:00:00.000Z represents the complete ISO-8601 for the dates.

  • It returns you 4 hours ahead of the time of your computer based on your region compared to UTC (global time). This is how JavaScript works.

  • To solve this you have several options: use this library link or simply work in the corresponding time zones. Personally and learned in SOes, it is recommended to work in UTC and transform the dates in the front-end.

  • More information here: link

    d = new Date();
    d.setUTCFullYear(2017);
    d.setUTCMonth(1); // Febrero
    d.setUTCDate(28); // OJO, es 28!
    d.setUTCHours(2); // 2 AM
    d.setUTCMinutes(45);
    d.setUTCSeconds(26);
    // -> 2017-02-28T02:45:26.884Z (Hora actual en UTC)
    console.log(d); 
    //La hora en que me encuentro es GMT-08 (hora del pacífico)
    //Por eso sale 8 horas antes, en otras palabras:
    //6PM (hora actual en mi zona horaria) + 8 horas (de diferencia con UTC) = 2AM (en UTC)
    console.log(d.toLocaleString());       // -> 02/27/2017, 6:45:26 PM 
    console.log(d.toLocaleDateString());   // -> 02/27/2017 //Esto es lo que buscas
    console.log(d.toLocaleTimeString());   // -> 6:45:26 PM
        
    answered by 28.02.2017 в 19:02
    0

    It is due to the time zone on the delivered date, since writing 2017-03-02T16:22:23.000Z is being specified with the UTC time (+0) and when it is printed it is presented with the local time, you can read more in link .

    You can print the time in different time zones with Date.prototype.toLocaleString() .

    Ex.

    const d = new Date('2017-03-02T16:22:23.000Z')
    
    console.log(d.toLocaleString('ln', {
      timeZone: 'America/New_York'
    }))
    console.log(d.toLocaleString('ln', {
      timeZone: 'Asia/Shanghai'
    }))
        
    answered by 02.05.2017 в 01:39