首页 > 解决方案 > 如何从客户端获取当前日期时间?

问题描述

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

下一个代码什么时候出现?

<div>@DateTime.Now</div>

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

标签: c#blazorblazor-server-side

解决方案


第一个解决方案:


使用 Blazored.Localisation nuget 包

在包管理器控制台中

Install-Package Blazored.Localisation

在 Startup.cs

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

在你看来

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

第二种解决方案:


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

JavaScript 文件中的代码

function getClientDate() {
var d = new Date();
document.getElementById("demo").innerHTML = d;
}

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

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


推荐阅读