【问题标题】:How to display current date and time using ionic如何使用离子显示当前日期和时间
【发布时间】:2021-11-21 23:37:48
【问题描述】:

在这里,我正在尝试使用离子框架开发移动应用程序。我想在我的应用程序中设置当前时间和日期。但它没有用。谁能帮我解决这个问题? 这是我的代码。

HTML 代码

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

ts。代码

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());
  });
}
 }

【问题讨论】:

  • 我认为你应该在https://stackoverflow.com/a/45263442/12482704下面的链接中查看这个答案
  • @RidwanAjibola 我之前检查过这段代码,但它没有给我一个正确的答案来解决这个错误
  • 要在 ion-datetime 上显示预设日期,您必须使用 [(ngModel)]="yourDateVariable"

标签: javascript ionic-framework ionic4


【解决方案1】:

您是否尝试过使用 [value] 属性而不是 ViewChild? 尝试这样做:

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

在你的 ts 文件中:

  dateTime;

  constructor() { }

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

这对我有用!

【讨论】:

    【解决方案2】:

    我尝试了从谷歌找到的另一个代码,它运行良好。 这是代码;

    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;
      });
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 2019-09-06
      • 2016-09-23
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      相关资源
      最近更新 更多