[英]How to get current DateTime from client?
我想用 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");
}
}
}
例如,您可以使用 Js 如下:
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
這將在用戶端運行並獲取用戶的本地時間
從客戶端獲取時區的最佳和最可靠的方法是向他們詢問。 通常,您會為用戶提供一個“個人資料”頁面,他們可以在其中更新時區、貨幣和格式等內容。 我建議這是一個更強大的解決方案。
如果您使用的是 Blazor 服務器端,請查看Blazor Time (它也適用於 webassembly)。
它允許您通過引入<ToLocal>
razor 組件轉換為本地。
<ToLocal DateTime="testUtcTime" Format="ddd mmm dd yyyy HH:MM:ss"></ToLocal>
要獲取客戶端操作系統時間,您必須使用 TimeZone 或者您可以使用 toLocaleDateString() 。 您可以使用以下代碼
<div>@DateTime.Now.toLocaleDateString()</div>
或者
<div>@new Date().toLocaleDateString()</div>
它可能會解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.