Live Chat Icon For mobile
Live Chat Icon

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

Platform: Blazor| Category : General, JavaScript Interop

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.

  1. 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 >

  2. Now display the UTC time and calculate the user time by using the offset time difference.
    [Index.razor]

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

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

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

Please submit your question and answer.