How do you convert the date and time to a client’s or user’s time zone in Blazor Server?

Platform: Blazor| Category : JavaScript Interop, General

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.

  1. 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 ValueTask GetLocalDateTime ( DateTimeOffset dateTime )
    {
    if (_userOffset == null)
    {
    int offsetInMinutes = await _jsRuntime.InvokeAsync("blazorGetTimezoneOffset");
    _userOffset = TimeSpan.FromMinutes(-offsetInMinutes);
    }
    return dateTime.ToOffset(_userOffset.Value);
    }
    }
    }

  2. To register the time zone service, add the following code snippet to the Program.cs file.
    [Program.cs]

    builder.Services.AddScoped();

  3. 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();
    }

  4. 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">

  5. Finally, you can utilize the service to display a date and time in your application.
    [Index.razor]

    @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);
    }
    }
    }
    Refer to this link for more details.

    View Sample in GitHub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.