Maximum range of 60 days in Angular between two date inputs

Viewed 137

I need in JavaScript or TypeScript for Angular that the entered start date is not greater than 60 days for the entered end date... the logic would be: "maximum range 60 days" between the two inputs (dateFrom to dateTo). Hello, I need JS or Angular TS so that the entered start date is not greater than 60 days for the entered end date... the logic would be: "maximum range 60 days" for the inputs.

datepicker(){
  var dateFrom = this.consultaForm.get('desdeCreacion').value;
  var dateTo = this.consultaForm.get('hastaCreacion').value;

  
  if(dateTo > (dateFrom < this.datePipe.transform(new Date(dateTo).getTime()-5100000000), 'yyyy-MM-dd')){
    alert('Rango máximo 60 dias');
    window.location.reload();}
  }
3 Answers

You could create a utility function just to calculate the differences in two dates, like so:

// Assuming fromDate and toDate are Date objects
// Otherwise you could convert them to Dates and pass here
function dayDifference(fromDate, toDate) {
  return Math.floor((toDate - fromDate)/(1000 * 60 * 60 * 24)) // Convert milliseconds to days
}

And then use this in your validation logic, like so:

if(dayDifference(dateFrom, dateTo) <= 60) {
    alert('Rango máximo 60 dias');
    window.location.reload();}
}

Thank you! I adapted your answers and I solved it like this:

  // Rango máximo 60 dias (sweetalert2)
  var dateFrom60 = this.datePipe.transform(new Date(dateFrom).getTime()+5150000000,'yyyy-MM-dd');
  if(dateTo > dateFrom60){
    this.hasta.reset();
    Swal.fire({
      icon: 'error',
      title: 'Rango máximo 60 días'
    })
  }

I feel like there is a better solution but you can you the Date Object and manipulate the date.

datepicker(){
  var dateFrom = new Date(this.consultaForm.get('desdeCreacion').value);
  var dateTo = new Date(this.consultaForm.get('hastaCreacion').value);

  
  if(dateTo > new Date(dateFrom.setDate(dateFrom.getDate() + 60)) ){
    alert('Rango máximo 60 dias');
    window.location.reload();}
  }

Related