我正在使用ng-bootstrap和ngbDatepicker作为日历,我想在从日历中选择开始日期时添加一天到endDate

时间:2018-04-02 07:40:30

标签: angular forms ng-bootstrap

我正在研究ngbDatepicker,我想在选择开始日期时将一天添加到日历中。 我的开始和结束日期格式如下:

 public startDate: NgbDate;
 public endDate: NgbDate;

当我选择开始日期时,我会以以下格式获取日期:

startDate :{year:2018,month:4,date:10}

我的HTML代码是:

<input required class="form-control" placeholder="dd-MM-YYYY" name="startDate" required ngbDatepicker #d="ngbDatepicker"
            formControlName="startDate" [minDate]="minDate" [readonly]="true" [formControl]="formModel.controls.startDate"
            [ngClass]="{'has-error':!formModel.controls['startDate'].valid && formModel.controls['startDate'].touched}"
          />
                 <input required class="form-control" placeholder="dd-MM-YYYY" name="endDate" ngbDatepicker #d2="ngbDatepicker" [formControl]="formModel.controls.endDate"
            [minDate]="minDate" [readonly]="true" [ngClass]="{'has-error':!formModel.controls['endDate'].valid  && formModel.controls['endDate'].touched}"
          />

和ts代码是:

  this.formModel.valueChanges.subscribe((e: any) => {
  var dateStart = e.startDate;
});

这里dateStart的格式为:

  {year:2018,month:4,date:10}

1 个答案:

答案 0 :(得分:0)

//create a change only for 'startDate', then, the argument is the  startDate itselft

this.formModel.get('startDate').valueChanges.subscribe((value: any) => {

  //create a javascript type Date, in typescript don't use "var", use "let"
  let date:any=new Date('' + value.year + '-' + value.month + '-' + value.day);

  //Add one day
  date=new Date(date.getTime()+24*60*60*1000);

  //create a ngbDateStructure, 
  //see that javaScript getMonth() return 0 to January,1 to Febrary.. 
  let endDate={ year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate() }

  //change the value of endDate
  this.formModel.get('endDate').setValue(endDate);
}

注意:在ng-bootstrap中是白天,而不是日期