Reputation: 1694
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?
Upvotes: 3
Views: 6476
Reputation: 1739
You can install TimeZoneConverter via NuGet.
Then, if you manage to pass in your header a timezone information like Europe/Berlin
, you could do the following in your backend:
using TimeZoneConverter;
...
string timezoneString = "Europe/Berlin";
TimeZoneInfo timezone = TZConvert.GetTimeZoneInfo(timezoneString);
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timezone));
Upvotes: 1
Reputation: 3486
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.
Upvotes: 1