To convert the date and time to a client’s or user’s time zone in Blazor Server, use the JavaScript function to get the current offset time difference from UTC in minutes using the new Date().getTimezoneOffset() method in Blazor using JavaScript Interop. Display the local time by the current offset time difference.
Follow these steps to convert the server time zone to the user’s time zone.
Add the JavaScript function using JS Interop. Get the current offset time from UTC in minutes using the new Date().getTimezoneOffset() method.
[_Host.razor]<body>
@*Requires render-server mode as "Server" while initializing the component to execute JavaScript in OnInitializedAsync.*@
<component type="typeof(App)" render-mode="Server" />
. . .
. . .
<script>
function GetTimezoneValue() {
// Returns the time difference in minutes between UTC time and local time.
return new Date().getTimezoneOffset();
}
</script>
</body >Now display the UTC time and calculate the user time by using the offset time difference.
[Index.razor]
Refer to this link for more details. View Sample in GitHub@page "/"
@inject IJSRuntime JsRuntime
<h1>Current DateTime</h1>
<p>Now (UTC): @DateTimeOffset.UtcNow.ToString()</p>
<p>Now (local): @localTime.ToString()</p>
@code {
private DateTimeOffset localTime;
private TimeSpan? userTime;
protected override async Task OnInitializedAsync()
{
if (userTime == null)
{
int timeDiffer = await JsRuntime.InvokeAsync<int>("GetTimezoneValue");
userTime = TimeSpan.FromMinutes(-timeDiffer);
}
// Converting to local time using UTC and local time minute difference.
localTime = DateTimeOffset.UtcNow.ToOffset(userTime.Value);
}
}
Share with