1

I am receiving from the server a date in UTC format (as a string) = "2020-04-01T00:00:00Z". When my users are visiting the calendar here in the UK (gmt) they can see it fine. However my users in the USA of course see the calendar pre-selecting 31st March.

How can I make my users in the USA also see the calendar pre-selecting 1st April?

I'm aware that PrimeNG removed the UTC="true" attribute.

Andrew Howard
  • 2,818
  • 5
  • 33
  • 59

1 Answers1

0

See if this works:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  dates: UTCDate[] = [];

  days: UTCDate[] = [];

  constructor() {
    for (var i = 0; i < 24; i+= 3) {
      this.dates.push(new UTCDate(new Date(Date.UTC(2018, 0, 1, i))));
    }

    for (var j = 1; j < 28; j+= 3) {
      this.days.push(new UTCDate(new Date(Date.UTC(2018, 0, j))));
    }
  }
}

class UTCDate {
  private boundDateBacker: Date;
  constructor(private dateInstance: Date) {
    this.boundDateBacker = this.utcToLocal(dateInstance);
  }

  public get boundDate(): Date {
    return this.boundDateBacker;
  }
  public set boundDate(value: Date) {
    if (value) {
      this.dateInstance.setTime(this.localToUtc(value).getTime());
      const newTime = value.getTime();
      if (newTime !== this.boundDateBacker.getTime()) {
        this.boundDateBacker.setTime(newTime);
      }
    }
  }

  private localToUtc(date: Date): Date {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(),  date.getHours(), date.getMinutes(), date.getSeconds()));
  }

  private utcToLocal(date: Date): Date {
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
  }
}

I didn't write it, I found it while looking for a solution to the utc issue. I haven't tested it because I don't need to implement timezone support yet, but thought you could have a look at this solution and maybe find what you are looking for.

I'm thinking the logic there could be used inside a directive, instead of a separate class.

StackBlitz