Home > Blockchain >  How to display current date and time using ionic
How to display current date and time using ionic

Time:09-30

Here I am trying to develop a mobile application using an ionic framework. I want to set the current time and date in my application. But it didn't work. Can anyone help me to solve this problem? Here is my code.

HTML code

<ion-datetime
#dateTime
displayFormat="MMM DD, YYYY HH:mm"
formControlName="myDate"></ion-datetime>

ts. code

export class App{
@ViewChild('dateTime') dateTime;

 form: FormGroup
 myDate: FormControl = new FormControl('', Validators.required)

 constructor(private fb: FormBuilder) {}

 ngOnInit() {
this.form = this.fb.group({
  myDate: this.myDate
});

setTimeout(_ => {
  this.dateTime.setValue(new Date().toISOString());
  });
}
 }

CodePudding user response:

have you tried to use [value] property instead of ViewChild? Try to do this:

<ion-content>
  <ion-datetime [value]="dateTime" displayFormat="MMM DD, YYYY HH:mm" ></ion-datetime>
</ion-content>

and in your ts file:

  dateTime;

  constructor() { }

  ngOnInit() {
    setTimeout(() => {
      this.dateTime = new Date().toISOString();
    });
  }

this worked out for me!

CodePudding user response:

I have tried another code found from google and it worked perfectly. Here is the code;

HTML

<ion-item>
<ion-datetime min="2021" max={{currentDate}} displayFormat= "DD/MM/YYYY  h:mm A" 
  [(ngModel)]="chosenDate"></ion-datetime>
</ion-item>
<p> Current date is {{currentDate}}</p>
<p> Chosen date is {{chosenDate}}</p>

ts.code

export class App implements OnInit {
 public currentDate: String;
 public chosenDate: String;
 constructor(public navCtrl: NavController,private platform:Platform) {
   this.currentDate = (new Date()).toISOString();
   this.chosenDate = this.currentDate;
  });
 }
}
  • Related