Positive date period validation gives Nan error

Asked

Viewed 136 times

-2

I got it on my JS

var inicioFerias = new Date($("#txtInitialVacancies").val());
var fimFerias = new Date($("#txtFinalVacancies").val());

var utc1 = Date.UTC(fimFerias.getFullYear(), fimFerias.getMonth(), fimFerias.getDate());
var utc2 = Date.UTC(inicioFerias.getFullYear(), inicioFerias.getMonth(), inicioFerias.getDate());

        var diffDays = Math.ceil((utc1 - utc2) / (1000 * 60 * 60 * 24)); 

alert("diff " + diffDays);

This happens:

data final= 02/06/2010
data inicial = 08/06/2020

It says that final date cannot be less than initial date and returns false, this is correct. Now if

data final = 31/07/2020
data inicial = 08/06/2020

Returns an Nan in diffDays and does not validate a vacation period longer than 30. I’ve done the same thing with Math.floor. Math.abs does not validate anything.

Edit

There is an error that I have picked up now. When I give getDate() on the date, I should return the date day and is returning me the month. Maybe that’s the problem

Edit2

I switched to that

var inicioFerias = new Date($("#txtInitialVacancies").val().split("/"));
var fimFerias    = new Date($("#txtFinalVacancies").val().split("/"));
var dateStart = inicioFerias.toLocaleDateString();
var dateEnd = fimFerias.toLocaleDateString();


var dd = (Date.parse(dateEnd) - Date.parse(dateStart)) / (1000*60*60*24);
alert("qdt " + dd);

var diffDays = dd;

And I’ll take the next one. When the End Date is less than the Start Date, fine, it works, but when the End Date is greater than the Start Date, I get an Nan

  • 1

    What is the value returned by $("#txtInitialVacancies").val() and $("#txtFinalVacancies").val()? If they are strings in the format dd/mm/yyyy (as "31/07/2020"), then you can give NaN even, since the builder of Date does not accept any string as parameter...

  • @hkotsubo, but when the dataFinal is less than the initial it validates correctly. That’s what I don’t understand. For example, in Data $("#txtInitialVacancies").val() I have it: Thu Aug 06 2020 00:00:00 GMT-0300 (Horário Padrão de Brasília)

  • The funny thing is that June 8 should be 06/8, not August 6. As already commented in your other question, read: https://answall.com/q/13046/5878. There you have explained how to calculate the difference in dates. Please try to read and understand what was done in the answers.

  • @Andersoncarloswoss, I don’t know why, but he’s taking the format month/day/year and I don’t know how to reverse it without breaking the date format

  • 1

    The format dd/mm/yyyy does not exist in ISO and is not supported by JS. We use this erroneously format.

  • but I give a getDate() and bring me month and not day. We use datepicker here

  • It is exactly there your mistake, when you give a getDate() it has already pulled the date in the correct format (as ours is wrong), you must inform the date format before the new Date(). That is, treat your string first.

  • 1

    Exactly, read about the class parameters Date and will understand the problem. We have given spoilers too much, we can not spoil the end of the story.

  • @Leonardogetulio, in my second Edit I give a toLocaledateString. When I calculate with the final date larger than the initial, returns an Nan. The opposite works

  • Bro, come on, forget the date, first do the following: take the value of your string Edit that will be in format dd/mm/yyyy ex: 08/06/2020 and makes it stay in a good format for javascript to recognize, I suggest this yyyy-mm-dd ex: 2020-06-08, after this you give the parse: new Date(variavelTratata) ex: new Date('2020-06-08'). If you don’t do this, it won’t work unless you use a third-party library for this.

  • 1

    The only string format that is guaranteed to work on all browsers the same way is "yyyy-mm-dd", any other format will be browser dependent and is not guaranteed to work. In the case of "07/31/2019", Chrome (and I don’t remember if Firefox either) interprets it as "month/day/year", and as in this case the "month" is 31, the date is invalid and it returns Nan. The way is to generate the string in the correct format, or break this string, extract the numeric values and pass to the constructor: new Date(ano, mes - 1, dia) (subtracts 1 of the month because January is zero)

Show 6 more comments

1 answer

3

If the date is in the format you reported 08/06/2020, then the problem is in the first lines, none of your implementations below is valid for dates:

var inicioFerias = new Date($("#txtInitialVacancies").val());
var inicioFerias = new Date($("#txtInitialVacancies").val().split("/"));

Do not work because the interface of new Date(data) expects a date in format:

new Date();//Atribui data e hora atual
new Date(ano, mês, dia, hora, minuto, segundo, milissegundo);
new Date(valor);//Inteiro em milisegundos
new Date(dataString);//String em alguns formato ISO-8601 (2020-06-08T00:00:00)

Reference: Documentation Date

You can change the date format in several ways, I would use regex:

var inicioFerias = new Date($("#txtInitialVacancies").val().replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$3-$2-$1"));

If you find understanding complex can give revert + Join in your second solution:

var inicioFerias = new Date($("#txtInitialVacancies").val().split("/").reverse().join("-"));
  • I decided to move the date to MM-dd-yyyy, and then do the calculation. As I did not answer and if yours works, I will mark your reply, Andreantunesvieira. I am on the train.

Browser other questions tagged

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