如何获取服务器日期和时间 [英] How to get Server Date and Time

查看:393
本文介绍了如何获取服务器日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个在vs2010中创建的winform。

这里我想显示服务器的日期和时间。



但是时间在运行模式就像时钟一样。



我有窗口专用服务器安装mssql。



我得到表单加载的日期和时间,但我想继续显示像系统时间一样运行的时间。



但是如果我使用计时器并在每次打勾时增加1秒,我们将在一段时间后从当前服务器时间增加约2-3分钟。



我想从服务器获得真正的更新时间。但是我不想每秒都要查询sql查询以获取时间。它给我带来了很大的麻烦..



请建议我在客户机器上制作一个真正的时钟

表示机器和服务器时间有点相同。



谢谢

Ram Kumar

Hi,

I have a winform which is created in vs2010.
Here I want to display server date and time.

But Time in running Mode just like clock.

I have window Dedicated Server with mssql install.

I get the date and time when form is load but i want to continus display time in running just like a system time.

But If i use timer and add 1 seconds on every tick its time we will be increase from current server time approx 2-3 min after some time.

I want to real update time from server. But I do not want to exqute sql query per second to get time. its create a big problem for me..

Please suggest me that I want to make a real clock on client machine
means machine and server time are little bit same.

thanks
Ram Kumar

推荐答案

除非您要求,否则无法从SQL服务器获取任何信息:SELECT查询几乎是唯一的方法。所以试试:

You can't get any information from SQL server unless you ask for it: and a SELECT query is pretty much the only way to do that. So try:
SELECT GETDATE()





但是,请不要每秒都这样做!

为什么不在应用程序启动时只读它一次,并将其存储为:



But please, don't do it per second!
Why not just read it once when you app starts, and store it as:

DateTime serverTime = GetDateAndTimeFromSQL();
TimeSpan serverDiff = DateTime.Now - serverTime;



然后,您可以使用TimeSpan值通过将差值添加到当前值来计算服务器时间您的机器的日期和时间。每隔几个小时重新检查一次应保持同步。


You can then use the TimeSpan value to work out what the server time is by adding the difference onto the current date and time for your machine. A re-check every couple of hours should keep them nicely in sync.


试试这些..



获取服务器的当前日期时间并将其转换为c#中的本地时间

Try these..

Get current date time from server and convert it into local time in c#
DateTime serverTime = DateTime.Now; // gives you current Time in server timeZone
DateTime utcTime = serverTime.ToUniversalTime; // convert it to Utc using timezone setting of server computer

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, tzi); // convert from utc to local



要在本地检查它,请更改您的计算机时区以匹配您的服务器。然后运行代码。我检查并且它工作正常。

前两行可以混合成一行,如下所示。具有更好的性能:


to check it locally , change your computer timezone to match your server. then run the code. I check and it's working fine.
the first two lines can be mixed into one line as below . that has a better performance :

DateTime utcTime = DateTime.UtcNow;





或查看此链接。



Link1 [ ^ ]



Link2 [ ^ ]


这篇关于如何获取服务器日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆