Search code examples
c#angulardatetimeasp.net-core-2.1

Angular 5 and .NET Core 2.1 API: Getting current time in user's timezone


This works but I was wondering if anyone has a better method.

Goal:

Get client's DateTime offset and return DateTime values in client's local time.

What I did:

On the front-end, I created a custom header and passed it in the request.

export class ItemService {
  baseUrl = environment.apiUrl;
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'TimeZone-Offset': `${new Date().getTimezoneOffset()}`
    })
  }

  constructur(private authHttp: HttpClient) { }

  getItems() {
    return this.authHttp.get<Item[]>(this.baseUrl + 'items', 
      { headers: this.httpOptions.headers });
  }
}

Then on the back-end, I pulled in the header value, converted it to an integer, then converted UTC time to local using the AddMinutes functionality.

public class ItemsController : Controller
{
  [HttpGet]
  public async Task<IActionResult> GetItems()
  {
    var currentTime = DateTime.UtcNow.AddMinutes(int.Parse(
      Request.Headers["TimeZone-Offset"] != StringValues.Empty
        ? Request.Headers["TimeZone-Offset"][0] : "0"));

    // ...logic to return items
  }

So, if the TimeZone-Offset header is added, the server will be able to convert DateTimes to the client's local time, otherwise, the DateTimes will be given in UTC. Is there a better way? Should I just leave everything UTC on the server, and then do a UTC to Local conversion on the client-side?


Solution

  • Make shure that you send every Timestamp as UTC to the client. Something like "2018-12-12T20:13:00.000Z". If you convert that to a JavaScript Date it should display automatically in the local time zone of the Browser.