Integration with JSON

Generally, the data which is received from the server is serialized in a JSON format.

The date object in JSON is an ISO8601-formatted date string. For more details, refer to the documentation on the JSON.stringify method. On the other hand, the DateTimePicker works only with JavaScript Date instances.

To bind the DateTimePicker to dates which are serialized as strings, handle the parsing process:

  1. Convert the JSON date strings into valid JavaScript Date objects by using the IntlService or any other suitable Date parser.
  2. Define the value input property of the component—the same approach applies to reactive and template-driven forms.
  3. Serialize the form value on form submit. This step can be omitted if using Angular's HttpClient to send the form value to a remote server as the latter serializes the body of the request by default.

The following example demonstrates how to set the value of the DateTimePicker.

@Component({
    selector: 'my-app',
    template: `
        <form #form="ngForm" (ngSubmit)="handleSubmit(form.value)">
            <div class="example-config">
                <strong>Output (submit form to peek): {{output}}</strong>
            </div>
            <div>
                <label>
                    <div>
                        Select check-in date and time:
                    </div>
                    <kendo-datetimepicker
                        name="checkIn"
                        [(ngModel)]="reservationData.checkIn"
                    >
                    </kendo-datetimepicker>
                </label>
            </div>
            <div>
                <button type="submit" class="k-button">Submit</button>
            </div>
        </form>
    `
})
export class AppComponent {
    public reservationData: { checkIn?: Date };
    public output: string;

    public ngOnInit() {
        // Parsed JSON.
        const rawData = { checkIn: "2019-06-01T19:00:00.000Z" };

        // Preprocess the stringified date before passing it to the DateTimePicker.
        this.reservationData = this.parseObjectDates(rawData);
    }

    public parseObjectDates(target: any): any {
        const result = Object.assign({}, target);

        Object.keys(result)
            .forEach(key => {
                const date = new Date(result[key]);
                if (!isNaN(date.getTime())) {
                    result[key] = date;
                }
            });

        return result;
    }

    public handleSubmit(value: any): void {
        this.output = JSON.stringify(value);
    }
}

In this article