Home > Mobile >  Maximum range of 60 days in Angular between two date inputs
Maximum range of 60 days in Angular between two date inputs

Time:04-27

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();}
  }

CodePudding user response:

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();}
  }

CodePudding user response:

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();}
}

  • Related