I want to show current client DateTime with a blazor component.
Which time does next code present?
<div>@DateTime.Now</div>
I think it will be server time. How can I get client OS time?
I want to show current client DateTime with a blazor component.
Which time does next code present?
<div>@DateTime.Now</div>
I think it will be server time. How can I get client OS time?
First Solution:
using Blazored.Localisation nuget package
in Package Manager Console
Install-Package Blazored.Localisation
in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddBlazoredLocalisation(); // This adds the IBrowserDateTimeProvider to the DI container
}
and in your view
@inject Blazored.Localisation.Services.IBrowserDateTimeProvider browserDateTimeProvider
@page "/"
<p>The current local time is: <strong>@currentLocalTime</strong></p>
@code {
string currentLocalTime = "";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) // Remove the firstRender check if you want the current local time displayed to continuously update.
{ // Leave the above firstRender check in place to ensure that the call to StateHasChanged() does not trigger an endless update loop.
var browserDateTime = await browserDateTimeProvider.GetInstance();
currentLocalTime = browserDateTime.Now.ToString();
StateHasChanged();
}
}
}
Second Solution:
like @Ibrahem Uwk said, add function in Separate JavaScript file and include it in _Host.cshtml or any file but not .razor file
Code in JavaScript file
function getClientDate() {
var d = new Date();
document.getElementById("demo").innerHTML = d;
}
and then call the function in your View
@page "/"
@inject IJSRuntime jsRuntime
...
<p id="demo"></p>
...
@code {
protected async override Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
// call your JS here
JSRuntime.InvokeVoidAsync("getClientDate");
}
}
}
The best and most reliable way to get the timezone from the client is to ask them for it. Usually you give your user's a "profile" page where they can update things like timezones, currency and formatting. I would suggest this as a more robust solution.
U can use Js as following for example :
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
And this will run in user side and get the local time for user
If you are using Blazor server side then check out Blazor Time (it also works with webassembly).
It lets you convert to local by introducing a <ToLocal>
razor component.
<ToLocal DateTime="testUtcTime" Format="ddd mmm dd yyyy HH:MM:ss"></ToLocal>
For getting the client os time , you have to use TimeZone or you can use toLocaleDateString() . You can use either below code
<div>@DateTime.Now.toLocaleDateString()</div>
or
<div>@new Date().toLocaleDateString()</div>
It may resolve your issue.