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

How to get current DateTime from client?

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

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

<div>@DateTime.Now</div>

我认为这将是服务器时间。我怎样才能获得客户 OS 的时间?

要获取客户端 os 时间,您必须使用 TimeZone 或者可以使用 toLocaleDateString() 。您可以使用以下任一代码

<div>@DateTime.Now.toLocaleDateString()</div>

<div>@new Date().toLocaleDateString()</div>

它可能会解决您的问题。

你可以像下面这样使用 Js :

<p id="demo"></p>

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

这将在用户端 运行 并获取用户

的本地时间

第一个解:


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

从客户那里获取时区的最好和最可靠的方法是向他们询问。通常,您会为用户提供一个 "profile" 页面,他们可以在其中更新时区、货币和格式等内容。我建议这是一个更强大的解决方案。

如果您使用的是 Blazor 服务器端,请查看 Blazor Time(它也适用于 webassembly)。

它允许您通过引入 <ToLocal> razor 组件转换为本地。

<ToLocal DateTime="testUtcTime" Format="ddd mmm dd yyyy HH:MM:ss"></ToLocal>