Pierre
Pierre

Reputation: 1256

Ionic ion-datetime: how to set default picker value

I have the following need: the end-user should input a datetime in a field that is empty. Thanks to the business logic, this datetime can be suggested by the app. So what I would like to do is that clicking on the empty field displays the suggested datetime in both the field and the ion-datetime component.

Here is my code:

In HTML

    <ion-datetime   displayFormat='YYYY-MM-DD HH:mm' 
                    pickerFormat='YYYY-MM-DD HH:mm'
                    text-center 
                    (click)="init_worked_time()" 
                    [(ngModel)]='worked_time'>                  
    </ion-datetime>

In Typescript

init_worked_time() {
    if (this.worked_time == undefined) {
        if (this.times.start_time != 0) { 
            let tzoffset = (new Date()).getTimezoneOffset() * 60000;
            this.worked_time = moment(this.times.start_time).subtract(tzoffset, 'milliseconds').toISOString().slice(0, -1);
        } 
    }
}

The problem is that the suggested value is well displayed in the field after clicking on it but the ion-datetime component shows the current UTC time (even not local time…)

enter image description here

Is there any better approach for such need? Or maybe is there any possibility to update programmatically the displayed value of the ion-datetime component?

Thanks!

Upvotes: 2

Views: 5264

Answers (1)

Melchia
Melchia

Reputation: 24314

You using momentJs which already by default use hte local time so there is no need to subtract the offset.

init_worked_time() {
    if (this.worked_time == undefined) {
        if (this.times.start_time != 0) { 
            this.worked_time = moment(this.times.start_time).format();
        } 
    }
}

In your HTML you need to use the event tap instead of click:

<ion-datetime displayFormat='YYYY-MM-DD HH:mm' 
                    pickerFormat='YYYY-MM-DD HH:mm'  (tap)="init_worked_time()"
                    text-center 
                    [ngModel]='worked_time'>                  
    </ion-datetime>

Here's an online DEMO

Upvotes: 3

Related Questions