如何从客户端获取当前日期时间?

3pe*_*per 2 c# blazor blazor-server-side

我想用 blazor 组件显示当前客户端 DateTime。

下一个代码出现在什么时间?

<div>@DateTime.Now</div>
Run Code Online (Sandbox Code Playgroud)

我认为这将是服务器时间。如何获得客户端操作系统时间?

Abd*_*rah 5

第一个解决方案:


使用 Blazored.Localisation nuget 包

在包管理器控制台中

Install-Package Blazored.Localisation
Run Code Online (Sandbox Code Playgroud)

在 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddBlazoredLocalisation(); // This adds the IBrowserDateTimeProvider to the DI container
}
Run Code Online (Sandbox Code Playgroud)

在你看来

@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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种解决方案:


就像@Ibrahem Uwk 所说的,在单独的 JavaScript 文件中添加函数并将其包含在 _Host.cshtml 或任何文件中,但不是 .razor文件

JavaScript 文件中的代码

function getClientDate() {
var d = new Date();
document.getElementById("demo").innerHTML = d;
}
Run Code Online (Sandbox Code Playgroud)

然后在您的视图中调用该函数

@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");
    }
 }
}

Run Code Online (Sandbox Code Playgroud)