Any system that has clients in multiple time zones is always problematic. With the rise in cloud services and containerized applications, it is frequently the case that your web or desktop clients do not use the same time as your server components (which are more frequently running in UTC). Typically this is dealt with by using DateTimeOffset instead of DateTime. But I’ve noticed that it doesn’t quite work as expected in Blazor WASM. While the actual DateTime value itself works as expected, the times are always displayed in GMT. Asking clients to work in GMT simply because the server or database does is not going to be acceptable.
The odd thing is that Blazor WASM seems to know the correct time zone offset:
<p> Local Time Zone: @TimeZoneInfo.Local.DisplayName<br /> Local Time Offset: @TimeZoneInfo.Local.BaseUtcOffset<br /> Local Time: @DateTimeOffset.Now.ToString("R") </p>
But, the Local Time displayed here is in GMT! Why? I haven’t really been able to find an answer, but plenty of similar complaints. The real oddity is as follows:
<p> Local Time: @DateTimeOffset.Now.LocalDateTime.ToString("g") </p>
I use the “g” format here because LocalDateTime is a DateTime property, without time zone information. This displays the correct local time! So why doesn’t DateTimeOffset.Now contain the correct offset information? This seems to remain a mystery.
Still, this is at least workable. The correct time is stored in the database and it is possible to display the local user’s time for DateTimeOffset values using the LocalDateTime property. A combination of this, plus the (correct, thankfully) data in System.TimeZoneInfo should provide all of the necessary components to display the time as desired.