Issue
I'm working on an ionic project, and have this error. I have have a button , I want print date that user select
My code
age.component.ts
import { Component, OnInit } from '@angular/core';
import * as moment from'moment';
@Component({
.....
})
export class AgeComponent implements OnInit {
dob:any = '' ;
myDate = {
years: 0,
months:0,
weeks:0,
days:0,
minutes:0,
seconds:0,
}
constructor() { }
calculateAge(){
let todaysDate = moment(new Date());
let dob = moment( new Date(this.dob) );
let duration = moment.duration(todaysDate.diff(dob));
this.myDate.years = duration.years();
this.myDate.months = Math.floor(duration.asMonths());
this.myDate.weeks = Math.floor(duration.asWeeks());
this.myDate.days = Math.floor(duration.asDays());
this.myDate.minutes = Math.floor(duration.asMinutes());
this.myDate.seconds = Math.floor(duration.asSeconds());
}
}
And here is my age.component.html code
<ion-datetime class="datetime" [(ngModel)]="dob" pickerFormat="MMM DD YYYY"
displayFormat="MMM DD, YYYY" min="1950-01-01" max="2050-01-01"></ion-datetime>
<ion-button (click)="calculateAge()" >Calculate</ion-button>
<span>{{myDate.years}} years</span>
<span>{{myDate.months}} months</span>
<span>{{myDate.weeks}} weeks</span>
<span>{{myDate.days}} days</span>
<span>{{myDate.minutes}} minutes</span>
<span>{{myDate.seconds}} seconds</span>
Solution
The NaN error only happens when you not select any date from ion-datetime
.
to solve that problem you can simply add condition in your variable let dob
to let dob = moment( new Date(this.dob ? this.dob : todaysDate));
TS
calculateAge(){
let todaysDate = moment(new Date());
let dob = moment( new Date(this.dob ? this.dob : todaysDate)); <-- add condition here
let duration = moment.duration(todaysDate.diff(dob));
this.myDate.years = duration.years();
this.myDate.months = Math.floor(duration.asMonths());
this.myDate.weeks = Math.floor(duration.asWeeks());
this.myDate.days = Math.floor(duration.asDays());
this.myDate.minutes = Math.floor(duration.asMinutes());
this.myDate.seconds = Math.floor(duration.asSeconds());
}
here's the sample
Answered By - Nicho
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.