Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-bootstrap datepicker format

I am using ng-bootstrap datepicker but when I save my form the date gets saved as.

date: {
  day: 01,
  month: 12,
  year: 16
}

I was hoping I could get it to save as something more like "2016-11-23T00:39:31.768Z"

Here is my implementation:

<div class="input-group">
  <button class="input-group-btn" (click)="d.toggle()" >
    <md-icon svgSrc="assets/images/calendar-plus.svg" style="cursor: pointer;"></md-icon>
  </button>
  <input class="form-control" placeholder="dd-mm-yyyy" name="dp" formControlName="due_date" navigation="arrows" ngbDatepicker #d="ngbDatepicker">
</div>

And form.component:

constructor( private fb: FormBuilder ) {
    this.form = this.fb.group({
      due_date: [''],
    });
  }
like image 782
Daimz Avatar asked Nov 24 '16 00:11

Daimz


2 Answers

You're using ng-bootstrap not ng2-bootstrap (different groups). The code behind it uses the NgbDateStruct which is an object { day, month, year }

On submission you'll need to hook in and change the value to something else, like:

onSubmit(): {
    let ngbDate = this.form.controls['due_date'].value;
    let myDate = new Date(ngbDate.year, ngbDate.month-1, ngbDate.day);
    let formValues = this.form.value;
    formValues['due_date'] = myDate;
    <...>
    http.post(url, formValues);
}

https://ng-bootstrap.github.io/#/components/datepicker

NgbDateStruct Interface of the model of the NgbDatepicker and NgbInputDatepicker directives

Properties

day Type: number The day of month, starting at 1

month Type: number The month, with default calendar we use ISO 8601: 1=Jan ... 12=Dec

year Type: number The year, for example 2016

like image 159
silentsod Avatar answered Sep 25 '22 09:09

silentsod


As @silentsod mentioned, you need to convert the date object that the datepicker uses from the NgbDateStruct format into a string format. ng-bootstrap provides a function to convert a date in the NgbDateStruct format to the ISO 8601 format (yyyy-mm-dd). You do not have to write your own if using that format:

import {NgbDateParserFormatter} from '@ng-bootstrap/ng-bootstrap';

...

constructor(private ngbDateParserFormatter: NgbDateParserFormatter; ... ) {
    ...
}

...

onSubmit(): {
    let ngbDate = this.form.controls['due_date'].value;
    let myDate = this.ngbDateParserFormatter.format(ngbDate); // e.g. myDate = 2017-01-01
    ...
}

See: https://github.com/ng-bootstrap/ng-bootstrap/blob/master/src/datepicker/ngb-date-parser-formatter.ts

like image 31
TiaanM Avatar answered Sep 26 '22 09:09

TiaanM