Search code examples
angulartypescriptionic-framework

why does console show error when I declare datetime in ionic


I'm new to ionic and Angular. I don't know where I went wrong here. The compiler error is:

node_modules_ionic_core_dist_esm_ion-app_8_entry_js.js:2 TypeError: Cannot destructure property 'month' of '(0 , _data_cb72448c_js__WEBPACK_IMPORTED_MODULE_9__.P)(...)' as it is undefined.
    at Datetime.processValue (ion-datetime_3.entry.js:702:15)
    at Datetime.componentWillLoad (ion-datetime_3.entry.js:1082:10)
    at safeCall (index-8e692445.js:1458:36)
    at dispatchHooks (index-8e692445.js:1315:23)
    at Array.dispatch (index-8e692445.js:1299:28)
    at consume (index-8e692445.js:2242:21)
    at flush (index-8e692445.js:2257:9) undefined

In the HTML file, I have an "ion-datetime" item.

<ion-item>
    <ion-datetime [(ngModel)]="dateTime">
    </ion-datetime>
  </ion-item>

In ts file, I declare dateTime as:

dateTime:Date=new Date();

I also tried to declare with values, but no luck here.

dateTime:Date=new Date('1990-12-20');

I have no clue what the issue is here, and I have struggled for hours. Any help would be appreciated. Thank you.


Solution

  • ion-datetime uses the ISO 8601 datetime format for its value. The value is simply a string, rather than using JavaScript's Date object. To resolve your problem, just simply declare the dateTime value as string. I recommend you use moment.js to format current time easily:

    <ion-datetime display-format="YYYY-MM-DD" [(ngModel)]="dateTime"></ion-datetime>
    dateTime:string=moment().format('YYYY-MM-DD');