简体   繁体   English

Blazor 服务器端:如何读出用户/浏览器的本地时间而不是服务器的本地时间(仅使用 c#)

[英]Blazor Server Side: How can I read out the local time of the user/browser not of the server (using only c#)

I have created a page where weather data is displayed for the user (I get the data via api call).我创建了一个页面,其中为用户显示天气数据(我通过 api 调用获取数据)。 I have the UTC-timestamp of the data from the api call.我有来自 api 调用的数据的 UTC 时间戳。

My problem is that if I transform the UTC time via ToLocalTime() the local time of my Server is presented not the local time of the users browser.我的问题是,如果我通过 ToLocalTime() 转换 UTC 时间,则显示的是我服务器的本地时间而不是用户浏览器的本地时间。

Is there a way to show the user "their" time: UTCTime.ToUserTimeZone() with C# and Blazor only?有没有办法只使用 C# 和 Blazor 向用户显示“他们的”时间:UTCTime.ToUserTimeZone()?

I have zero knowledge of JS etc. or is that the only way.我对 JS 等零知识,或者这是唯一的方法。 I googled and found alot of answeres where I have to implement JavaScript to "get" the user localisation.我用谷歌搜索并找到了很多答案,我必须实现 JavaScript 来“获取”用户本地化。

Thanks for your help and time感谢您的帮助和时间

It's not possible to get the user time without javascript.没有 javascript 就不可能获得用户时间。
If you use Blazor Server Side, the C# Code runs on the server.如果使用 Blazor 服务器端,则 C# 代码在服务器上运行。 But you can call javascript functions.但是你可以调用javascript函数。
See https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1请参阅https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1

Here is a javascript to get the user date and timeoffset (add the script tag inside the header element of your _Host.cshtml):这是一个用于获取用户日期和时间偏移的 javascript(在 _Host.cshtml 的标题元素中添加脚本标记):

<script>
    window.localDate = () => {
        var ldCurrentDate = new Date();
        return ldCurrentDate.getFullYear() +
            "-" + String(ldCurrentDate.getMonth() + 1).padStart(2, '0') +
            "-" + String(ldCurrentDate.getDate()).padStart(2, '0') +
            "T" +
            String(ldCurrentDate.getHours()).padStart(2, '0') +
            ":" + String(ldCurrentDate.getMinutes()).padStart(2, '0') +
            ":" + String(ldCurrentDate.getSeconds()).padStart(2, '0');
    };
    window.utcDate = () => {
        var ldCurrentDate = new Date();
        return ldCurrentDate.getUTCFullYear() +
            "-" + String(ldCurrentDate.getUTCMonth() + 1).padStart(2, '0') +
            "-" + String(ldCurrentDate.getUTCDate()).padStart(2, '0') +
            "T" +
            String(ldCurrentDate.getUTCHours()).padStart(2, '0') +
            ":" + String(ldCurrentDate.getUTCMinutes()).padStart(2, '0') +
            ":" + String(ldCurrentDate.getUTCSeconds()).padStart(2, '0');
    };
    window.timeZoneOffset = () => {
        return new Date().getTimezoneOffset() / 60;
    };
</script>

Call from C#:从 C# 调用:

@page "/dates"
@inject IJSRuntime JSRuntime;

<button type="button" @onclick="GetDates">
    Get Dates
</button>

<p>
    <span>
        User Date: @string.Format("{0:G}", this.UserDate)
    </span>
</p>
<p>
    <span>
        Utc Date: @string.Format("{0:G}", this.UTCDate)
    </span>
</p>
<p>
    <span>
        TimeZoneOffset: @string.Format("{0}", this.TimeZoneOffset)
    </span>
</p>
<p>
    <span>
        ServerDate: @string.Format("{0:G}", this.ServerDate)
    </span>
</p>


@code {

    private DateTime UserDate { get; set; }
    private DateTime UTCDate { get; set; }
    private DateTime ServerDate { get; set; }
    private int TimeZoneOffset { get; set; }


    private async Task GetDates()
    {
        this.ServerDate = DateTime.Now;
        this.UserDate = await JSRuntime.InvokeAsync<DateTime>("localDate");
        this.UTCDate = await JSRuntime.InvokeAsync<DateTime>("utcDate");
        this.TimeZoneOffset = await JSRuntime.InvokeAsync<int>("timeZoneOffset");
    }
}

You can read out local and UTC time and receive .NET DateTime type from JS much simpler:您可以更简单地读取本地和 UTC 时间并从 JS接收 .NET DateTime 类型

  • Local time: new Date().toISOString();本地时间: new Date().toISOString();
  • UTC time: new Date().toUTCString(); UTC时间: new Date().toUTCString();

Also note in .NET 5 JS Interop changed a lot.还要注意 .NET 5 JS Interop 发生了很大变化。 Please check out new IJSRuntime Interface and also JS Isolation docs as well.请查看新的IJSRuntime Interface以及JS Isolation文档。

By using .NET 5 JS isolation (calling JS functions are very similar but slightly changes, see docs above):通过使用 .NET 5 JS 隔离(调用 JS 函数非常相似但略有变化,请参阅上面的文档):

export function localDate() {
  return new Date().toISOString();
}
export function utcDate() {
  return new Date().toUTCString();
}

I ran into a similar problem and created a library called Blazor Time to address it.我遇到了类似的问题,并创建了一个名为Blazor Time的库来解决它。

To install BlazorTime run Install-Package BlazorTime要安装 BlazorTime,请运行Install-Package BlazorTime

Then add <script src="_content/BlazorTime/blazorTime.js"></script> to your host or index file然后将<script src="_content/BlazorTime/blazorTime.js"></script>到您的主机或索引文件

After that you can display values in the users local time with the <ToLocal> tag之后,您可以使用<ToLocal>标记以用户本地时间显示值

<p>
  @*UTC to browser time*@
  <ToLocal DateTime="testUtcTime" Format="ddd mmm dd yyyy HH:MM:ss"></ToLocal>
</p>

<p>
  @*server time to browser time*@
  <ToLocal DateTime="testServerTime" Format="default"></ToLocal>
</p>

<p>
  @*display as iso example 2021-05-10*@
  <ToLocal DateTime="testUtcTime" Format="yyyy-mm-dd"></ToLocal>
</p>

<p>
  @*display as time example 2pm*@
  <ToLocal DateTime="testUtcTime" Format="htt"></ToLocal>
</p>

<button @onclick="Update">Update Time</button>

@code {
  private DateTime testUtcTime = DateTime.UtcNow;
  private DateTime testServerTime = DateTime.Now;

  private void Update()
  {
    testUtcTime = DateTime.UtcNow;
    testServerTime = DateTime.Now;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Blazored 在 Blazor 服务器端读取和写入本地存储? - How do I read and write to the local storage in Blazor server side using Blazored? 如何确定服务器端 C# 上的浏览​​器窗口大小 - How can I determine browser window size on server side C# 如何在C#中的应用程序中在客户端获取远程服务器的日期和时间? - How can I get the remote server's date and time at the client side in my application in c#? 使用 Blazor 服务器端 - Using Blazor server side 如何在 Blazor 服务器端的 CircuitHandler 中调用方法? - How can I invoke method in CircuitHandler of Blazor server-side? 如何确保C#应用程序只能从SQL Server数据库读取? - How can I ensure that my C# application can only read from the SQL Server databases? 用户单击浏览器停止按钮时如何停止服务器端处理(ASP.net C#) - How to stop server side processing when user clicks browser stop button (ASP.net C#) 如何从 Blazor 服务器写入浏览器控制台 - How can I write to browser console from Blazor Server 如何使用 .Net (C#) 在服务器端将原始 HTML 转换为 Markdown? - How can I convert raw HTML to Markdown, server-side using .Net (C#)? 如何使用C#序列化对象数组服务器端? - How can I serialize an object array server side using c#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM