c# - 如何从客户端获取当前日期时间?
问题描述
我想使用 blazor 组件显示当前客户端 DateTime。
下一个代码什么时候出现?
<div>@DateTime.Now</div>
我认为这将是服务器时间。如何获取客户端操作系统时间?
解决方案
第一个解决方案:
使用 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");
}
}
}
推荐阅读
- azure-devops - 如何使用 Azure DevOps Rest API 在发布中启动特定阶段
- python - 计算矩阵的 log2
- bash - 登录到 /var/log/ 时出现权限被拒绝错误
- python - ImporError:没有名为“win32com”Python 3.4 的模块
- apache-spark - Spark 任意状态流聚合,flatMapGroupsWithState API
- php - Laravel/PHP:如何验证渲染字段?
- android - 评估项目 ':app' 时出现问题
- .htaccess - 如何限制管理员 url 访问某些 IP 地址
- crashlytics - Crashlytics 与 SwiftyBeaver
- ios - 如何使用数组创建 NSPredicate 包含元素