简体   繁体   English

服务器上的DateTime.Now问题

[英]Problem with DateTime.Now on Server

I have a great problem and I don't know how to solve it 我有一个很大的问题,我不知道如何解决

I have created a web application and host it in USA server , and the users who access this web application from Egypt 我已经创建了一个Web应用程序并将其托管在USA服务器中,并且从埃及访问该Web应用程序的用户

The problem that i'm using DateTime.Now method inside the application and this method return the time of USA server not the time of the machine that use it in Egypt 我在应用程序内部使用DateTime.Now方法的问题,此方法返回美国服务器的时间,而不是埃及使用它的机器的时间

How can i solve this problem ? 我怎么解决这个问题 ? please help me as soon as you can 请尽快帮助我

Thanks in Advance 提前致谢

Well, you could start off by using DateTime.UtcNow , transferring that to the client, and then performing the relevant time zone conversions at the client. 好吧,您可以通过使用DateTime.UtcNow开始,将传输到客户端,然后在客户端执行相关的时区转换。 That's usually a reasonable way of working - so long as you can do the processing at the client (eg in JavaScript). 这通常是一种合理的工作方式-只要您可以在客户端进行处理(例如,在JavaScript中)。

Alternatively, ask the user their time zone so you can serve pages which use the local time, using TimeZoneInfo . 或者,询问用户他们的时区,以便您可以使用TimeZoneInfo服务使用当地时间的页面。 Of course if you know all your users are in Egypt you could potentially just hard-code that. 当然,如果您知道所有用户都在埃及,则可以将其硬编码。

You need to convert the datetime value to the time zone of your users. 您需要将datetime值转换为用户的时区。 One simple way to do this would be to call ConvertTime and pass in the desired time zone as follows: 一种简单的方法是调用ConvertTime并传递所需的时区,如下所示:

DateTime now = TimeZoneInfo.ConvertTime(DateTime.UtcNow, 
    TimeZoneInfo.FindSystemTimeZoneById("Egypt Standard Time"));

Generate the time using UTS, so that it is normed, and then display based on the location of the user or on their preferences. 使用UTS生成时间,以使其标准化,然后根据用户的位置或他们的喜好进行显示。

You may want to read this also: Creating a DateTime in a specific Time Zone in c# fx 3.5 您可能还需要阅读以下内容: 在c#fx 3.5中的特定时区中创建DateTime

好了,您可以使用DateTime.UTCNow ,然后将其转换为本地时间。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM