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 GetLocalDateTime() 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.
To define the TimeZoneService class and the GetLocalDateTime() method, create a new file named TimeZoneService.cs in your project. Inside the TimeZoneService.cs file, define the TimeZoneService class and implement the GetLocalDateTime() method.
using Microsoft.JSInterop;
namespace BlazorServerApp
{
public class TimeZoneService
{
private readonly IJSRuntime _jsRuntime;
private TimeSpan? _userOffset;
public TimeZoneService ( IJSRuntime jsRuntime )
{
_jsRuntime = jsRuntime;
}
public async ValueTaskGetLocalDateTime ( DateTimeOffset dateTime )
{
if (_userOffset == null)
{
int offsetInMinutes = await _jsRuntime.InvokeAsync("blazorGetTimezoneOffset");
_userOffset = TimeSpan.FromMinutes(-offsetInMinutes);
}
return dateTime.ToOffset(_userOffset.Value);
}
}
}To register the time zone service, add the following code snippet to the Program.cs file.
[Program.cs]builder.Services.AddScoped
(); Create a JavaScript file named BlazorInterop.js within the wwwroot directory and include the provided code snippet in it.
[BlazorInterop.js]function blazorGetTimezoneOffset() {
return new Date().getTimezoneOffset();
}To add a reference to the JavaScript file, open the Pages/_Layout.cshtml or _Host.cshtml file, and include the following line of code:
[_Layout.cshtml/_Host.cshtml]<script src="~/BlazorInterop.js">
Finally, you can utilize the service to display a date and time in your application.
[Index.razor]
Refer to this link for more details. View Sample in GitHub@page "/"
@inject TimeZoneService TimeZoneService
<h1>Current date and time</h1>
<p>Now (UTC): @DateTimeOffset.UtcNow.ToString()</p>
<p>Now (local): @localTime.ToString()</p>
@code {
DateTimeOffset localTime;
protected override async Task OnAfterRenderAsync ( bool firstRender )
{
if (firstRender)
{
// TODO: Require server render mode while instantiating the component to execute JavaScript in OnInitializedAsync.
// In _Host.cshtml:
localTime = await TimeZoneService.GetLocalDateTime(DateTimeOffset.UtcNow);
}
}
}
Share with