How can I show the time in local time? For example, I would expect new Date().toISOString()
to show the current time relative to me, not the utc time.
Use moment. It’s far better than JavaScript’s Date
s.
I used new Date()
just to make my question simple, but I have to same problem if I do moment().toISOString()
. Right now, it’s 6:30am but the datetime says 10:30am.
toISOString
deliberately uses UTC. Try format
.
My scenary odata services,return datetimes as ISO 8601 UTC
The dates are declared in my model’s interfaces
DateProperty:Date
Model object (for sample only one Date field used)
{ExpectedEndDate:"2016-12-01T04:00:00Z"}
I use pipe to show in primeng DataTable, yes, i merge it with ionic2
<p-column field="ExpectedEndDate" header="F.Prevista">
<template let-col let-item="rowData" pTemplate type="body">
<span>{{item[col.field] | date: 'dd/MM/yyyy HH:mm:ss'}}</span>
</template>
</p-column>
this show the date in my local time as expected (GMT+0100)
01/12/2016 05:00:00
Using Ionic DateTime over my model’s property, show the edited date as UTC
for solve i do this in my form.ts
Declare 2 functions (i presume can be some kind of global)
setIonicDateTime(value: string): Date {
if (value) {
let date: Date = new Date(value);
let ionicDate = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
return ionicDate;
}
return null;
}
getIonicDateTime(value: Date): string {
if (value) {
let date: Date = new Date(value);
let ionicDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
return ionicDate.toISOString();
}
return null;
}
then wrap my model propery (edit is my model)
@Input() set ExpectedEndDate(value: string) {
this.edit.ExpectedEndDate = this.setIonicDateTime(value);
}
get ExpectedEndDate():string {
return this.getIonicDateTime(this.edit.ExpectedEndDate);
}
in the template the code for for the date use the property instead of model one.
<ion-item>
<ion-label floating>F.Prevista</ion-label>
<ion-datetime formControlName="ExpectedEndDate" displayFormat="DD/MM/YYYY HH:mm" [(ngModel)]="ExpectedEndDate">
</ion-datetime>
</ion-item>
This way works fine for me, allways show and edit the dates in local time and store in UTC.
this work allways the dates are ISO 8601 UTC
Naturally things change with time. Perhaps you’d like to update that post above for future visitors?
As an alternative, I ended up using Angular’s DatePipe:
I would love to, but Discourse (the software that powers the forums) locks you out from editing after a certain timeframe.
oh, right, I forgot about that feature (that I hate a bit).
Thanks!