0

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 :)

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Mohammad Shadmehr
  • 675
  • 11
  • 26
  • why do you ask questions if you don’t want to accept other’s answer or you already have answer? – Vivek Nuna Feb 27 '18 at 07:57
  • @vivek-nuna Well it is not always the case! The answer that I put for this question is not actually an answer! I put there like that as more details of my issue did not know that I could have edited my original question and add more to it! :) Your answer partially resolved my issue but I am still dealing with the UTC time is sent back an forth from server to client. I have also raised an issue in that regard [here](https://github.com/aspnetboilerplate/aspnetboilerplate/issues/3125) – Mohammad Shadmehr Feb 28 '18 at 10:18

1 Answers1

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:

  1. Assume this the UTC time saved in DB: 2018-02-23 00:00:00
  2. 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
  3. I save the form without changing the above value
  4. 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.
  5. Then I have a new value for the field without changing it in the form (2018-02-22 13:30:00)!
Mohammad Shadmehr
  • 675
  • 11
  • 26