Search code examples
angularangular5date-pipe

How to convert a date string to timezone specific date.?


Hi I am having an angular 5 project. I have issues with displaying dates based on the users timezone.

Here is my sample snippet of code.

  formatDateForTableDisplay(dateValueAsString: string) {

    console.log(dateValueAsString); // this will print for example 2020-05-31

    const dateObject = new Date(dateValueAsString);

    if (this.formGroup.get('frequency').value === 'PER_DAY') {
      return this.datePipe.transform(dateObject, 'mediumDate');
    } else if (this.formGroup.get('frequency').value === 'PER_MONTH') {
      return this.datePipe.transform(dateObject, 'LLL, yyyy');
    } else {
      return this.datePipe.transform(dateObject, 'yyyy');
    }
  }

The problem is imagine if we pass the date string as 2020-05-31 to the function formatDateForTableDisplay. In another users , timezone this is could be 1st of June as the users timezone is +8 hours ahead of GMT , this needs to be printed as 2020-06-01 . how can i achieve it

thank you


Solution

  • You have dateValueAsString coming in as 2020-05-31, meaning you don't have a hours, minutes, or seconds (hours is the most important one in this case). So you can't tell if dateValueAsString was saved at 2am (meaning it would stay as 2020-05-31) or if it was saved at 11pm (meaning it should be converted to 2020-06-01)