问题
I have a DateTime field in popup modal as below that is supposed to only show the time part:
HTML:
<div class='input-group date'>
<input class="form-control" type="datetime" #RequiredByDate name="RequiredByDate" [value]="formatDate(hitchRequest.requiredByDate, 'LT')" required>
<span class="input-group-addon">
<span class="fa fa-clock-o"></span>
</span>
</div>
TS:
formatDate(date: any, format: string): string {
if (!date) {
return '';
}
return moment(date).format(format);
}
onShown(): void {
$(this.requiredByDate.nativeElement).datetimepicker({
locale: abp.localization.currentLanguage.name,
format: 'LT',
});
}
When I set the DateTime and hit the save button the momentjs truly converts it to UTC time and send it to the server and eventually it is saved in DB in UTC time. My question is about when reading the data back from the server to the field. I assumed that the moment.js would reconvert it back to the local timezone like what it does when setting its value which seems it is not the case!
Any input is much appreciated :)
回答1:
I ended up with changing my formatDate method to following:
formatDate(date: any, format: string): string {
return moment.utc(date.toString()).local().format(format);
}
It show the local time when getting the value from DB, but now the issue is when updating its value. When I save the form it considers the date to a local time and everytime it deducts 10:30 from it and then send to the server!
Here is the scenario:
- Assume this the UTC time saved in DB: 2018-02-23 00:00:00
- On populating the field it adds 10:30 (my local time zone) to it and shows it in the field: 2018-02-23 10:30:00
- I save the form without changing the above value
- The moment deducts 10:30 hours from the returned value from the server (2018-02-23 00:00:00) again and sends it to the server to be saved.
- Then I have a new value for the field without changing it in the form (2018-02-22 13:30:00)!
来源:https://stackoverflow.com/questions/48922462/locale-datetime-in-abp