Home > Software engineering >  Day 31 changing to day 1 in typescript
Day 31 changing to day 1 in typescript

Time:11-13

When a put day 31 in the input field, the JSON 'dt_ini_vigencia' and 'dt_fin_vigencia' is changing for day 1. could anyone help me understand this?

JSON date format in input: '2022-12-31T03:00:00.000Z' this is what the JSON returns after this function: '2022-12-01T03:00:00.000Z' to 'dt_ini_vigencia' '2023-12-01T03:00:00.000Z' to 'dt_fin_vigencia'.

this problem only happens when a put day 31 in the input

`

var cotacaoJson = JSON.parse(resp[0].ds_cotacao_json);
          var date = new Date();
          date.setDate(cotacaoJson.dt_ini_vigencia.substring(8, 10)); //apparently is on this line
          date.setMonth(cotacaoJson.dt_ini_vigencia.substring(5, 7) - 1);
          date.setFullYear(cotacaoJson.dt_ini_vigencia.substring(0, 4));
          date.setHours(0);
          date.setMinutes(0);
          date.setSeconds(0);
          date.setMilliseconds(0);

          var dateF = new Date();
          dateF.setDate(cotacaoJson.dt_fin_vigencia.substring(8, 10));
          dateF.setMonth(cotacaoJson.dt_fin_vigencia.substring(5, 7) - 1);
          dateF.setFullYear(cotacaoJson.dt_fin_vigencia.substring(0, 4));
          dateF.setHours(0);
          dateF.setMinutes(0);
          dateF.setSeconds(0);
          dateF.setMilliseconds(0);

          this.cotacao = cotacaoJson;

          if (!this.editar)
          {
            this.cotacao.clausulas_particulares = 'N/A';
          }

          this.cotacao.dt_ini_vigencia = date;
          this.cotacao.dt_fin_vigencia = dateF;

`

save the 31st in date and dateF

CodePudding user response:

It is because new Date() returns the current date. It is November now, so the maximum date you can pass is 30. To fix this first set year, then a month, and only then a date

CodePudding user response:

Just use some robust and well tested library function for date parsing like parseJSON from date-fns rather than re-inventing the wheel.

  • Related