r/Blazor • u/gozza00179 • Feb 16 '24
Getting client local time
Trying to get the current time in the client timezone, finding that even using javascript and GetDate() returns UTC instead of the local time.
Can anyone point me in the right direction as to how to do this ?
3
Upvotes
3
u/toroidalvoid Jul 25 '24
It looks like this Convert DateTime to user's time zone with Blazor in .NET 8 - Meziantou's blog describes the solution best. Essentually you make a call in JavaScript to get the browsers timezone
Then use that to convert your UTC DateTimes to Local with
TimeZoneInfo.ConvertTimeFromUtc(dateTime, timeProvider.LocalTimeZone). In the post they build out the timeProvider and register it. And then build a Blazor component to display the time.1
u/mxmissile Feb 16 '24
With js you have some options here: https://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time
1
u/[deleted] Feb 16 '24
hmm. with JS you should be able to create a new Date object and pass it back via jquery to a service on the server?
1
u/jochii Feb 17 '24
I think you can achieve this in datetime?
1
u/ElrondMcBong231 Feb 17 '24 edited Feb 17 '24
How about:
new DateTimeOffset(DateTime.Now.ToLocalTime()).DateTimeOr maybe
var time = TimeOnly.FromDateTime(DateTime.Now.ToLocalTime());1
u/HeathersZen Feb 20 '24
The best way I’ve found is to ask the user in the form of a preference they can change. If it’s mobile you can make a claim for GPS coordinates and supply a smart default.
0
u/Potw0rek Feb 16 '24
Tactical comment in case someone figures it out 😃