angularionic-frameworkmomentjsangular2-databinding

ion-datetime bind to epoch


I have a model that requires the date/time as milliseconds in Unix Epoch format. I have tried using the Moment interface, Date | numeric as type and I can't seem to get it right.

I want the control to display in human readable format and the picker likewise but I want the databound model to be numeric. I can't use a pipe ("Cannot have a pipe in an action expression"). Should I remove the two way databinding, translate the value in the changeModel function and populate the person.date_of_birth with a similar function?

.html

<ion-datetime displayFormat="MMM DD, YYYY" pickerFormat="MMM DD, YYYY" (ngModelChange)="changeModel($event)" [(ngModel)]="person.date_of_birth"></ion-datetime>

.ts:

let person={name: string, date_of_birth: numeric};

The model is written to a local database on the mobile (pouchdb/sqlite) and then synched with a mongodb database via nodejs REST API. It is only displayed on this one html page so I'd really like it to be numeric everywhere else.


Solution

  • As input for your ion-datetime, you can use public yourDate: string = new Date().toISOString();. So this is the value you want to bind to your ion-datetime.

    If you want to have another format, you can do something like this new Date(yourDate).getTime(). If you have this ISOString, you can always parse it back to a Date object.

    Update

    Working with a pipe and a format function.

    Here we have a one-way databinding that is using my custom date pipe, thats formatting an numeric date to an ISOString. The (ngModelChange) event is the "other-way" binding, thats assigning back a numeric value to date_of_birth (format is a custom function).

    page.html

    <ion-datetime displayFormat="MMM DD, YYYY" 
        (ngModelChange)="date_of_birth=format($event)" 
        [ngModel]="date_of_birth | date"></ion-datetime> 
    

    date.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'date'
    })
    export class DatePipe implements PipeTransform {
    
      transform(value: any, args?: any): any {
        return new Date(value).toISOString();
      }
    
    }
    

    page.ts

    date_of_birth: number = new Date().getTime();
    
    format(val) {
      return new Date(val).getTime();
    }
    

    Working StackBlitz