How to get selected date from ionic-2 calendar onchange() method

微笑、不失礼 提交于 2020-02-06 07:30:47

问题


I am using ion2-calendar.

this is my html:

 <ion-calendar [(ngModel)]="date"
              (onChange)="onChange($event)"
              [type]="type"
              [format]="'YYYY-MM-DD'">
</ion-calendar>

and this is onchange in ts:

onChange($event) {

      console.log("onchange event called");
      console.log(moment().format('DD-MM-YYYY'));  
    }

This is my console:

onSelect event called
25-06-2018

But i am always getting current month and year,no matter which date I choose. Only the date value is changing. Its showing current month and year in the console for all dates. Can someone tell me how to get selected date in dd-mm-yy format from $event object.

Edit- This is what i get for console.log($event)

Moment {_isAMomentObject: true, _i: 1530297000000, _isUTC: false, _pf: {…}, _locale: Locale, …}
_d
:
Sat Jun 30 2018 00:00:00 GMT+0530 (India Standard Time) {}
_i
:
1530297000000
_isAMomentObject
:
true
_isUTC
:
false
_isValid
:
true
_locale
:
Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", ordinal: ƒ, _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, …}
_pf
:
{empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -2, charsLeftOver: 0, …}
__proto__
:
Object

It shows correct date of click. It would be great if someone could tell me how to extract date from this .


回答1:


$event of OnChange() is a moment object.

you can format like this: $event.format('DD-MM-YYYY')




回答2:


moment() statement always generates current time like new Date().

you should use a statement like moment("1995-12-25") or other various statements.

For details, please have a look at this moment.js docs


update

To say the conclusion first,

.html (nothing changed)

<ion-content padding>
  <ion-calendar [(ngModel)]="date"
  (onChange)="onChange($event)"
  [type]="type"
  [format]="'YYYY-MM-DD'">
</ion-calendar>

.ts

onChange(event) {
  console.log(event.format('DD-MM-YYYY')); // For actual usage.
  console.log(moment(event).format('DD-MM-YYYY')); // the statement you might think about
}

the above code gives you what you want.

What I want to say is that you should not use moment() but moment(event). Because moment() returns moment instance which has current time while moment(event) returns moment instance which has the time event carries.



来源:https://stackoverflow.com/questions/51022756/how-to-get-selected-date-from-ionic-2-calendar-onchange-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!