Search code examples
ng-bootstrapngb-datepicker

how calculate difference or compare(is bigger or not) between to data(Jalali calendar)


I use two ngb-datepicker in a page, of course jalali calendar, and bind to these two model:

dateModelFrom: NgbDateStruct;
dateModelTo: NgbDateStruct;  

after user select dates, i have 2 jalali date with ngb date structure:

dateModelFrom = {day: 1, month: 1, year: 1398}
dateModelTo = {day: 3, month: 1, year: 1398}  

now, I need to calculate difference between two dates, and check if fromDate is less than toDate or not.

i can use (https://github.com/alihoseiny/ngx-persian) or (https://momentjs.com/) and convert these two date and then calculate, but this can not be good, I think must be shorter solution.

also i know there is NgbDateNativeAdapter service(https://ng-bootstrap.github.io/#/components/datepicker/api#NgbDateNativeAdapter), i try to convert to javascript Date, and then calculate, but output is same as input:

let toDay:NgbDateStruct = this._persianNgbCalendar.getToday();;
let _toDay:Date = this._ngbDateNativeAdapter.toModel(toDay);

Solution

  • In the documenation from ngb-datepicker you will find an example for a range picker and there is a implementation for comparing two dates. Also you can check the stackblitz for better understanding.

    Example:

    <ngb-datepicker #dp (select)="onDateSelection($event)" [displayMonths]="2" [dayTemplate]="t" outsideDays="hidden"></ngb-datepicker>
    

    In your onDateSelection function you can compare two dates:

    onDateSelection(date: NgbDate) {
      if (!this.fromDate && !this.toDate) {
        this.fromDate = date;
      } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
        this.toDate = date;
      } else {
        this.toDate = null;
        this.fromDate = date;
      }
    }