【发布时间】:2014-12-05 09:28:50
【问题描述】:
我必须根据用户时区 ID 向用户显示日期和时间。我不能依赖用户电脑日期时间和设置。我在谷歌搜索方式并得到了下面的代码。代码似乎会查询许多外部服务器的日期和时间,但我不清楚我可以从下面的代码中得到什么样的日期和时间。
有些时候我需要印度时间。有时我需要伦敦时间,有时我需要其他国家的当地时间。很少有县有很多时区,这就是为什么我要发送时区 ID/名称并希望根据时区 ID/名称获取日期时间。
所以请指导我如何自定义以下代码,我可以在其中发送用户方的时区 ID,即使用户 pc 日期时间设置错误,例程也会根据时区 ID 返回正确的本地时间。寻找好的帮助。谢谢
public static DateTime GetFastestNISTDate()
{
var result = DateTime.MinValue;
// Initialize the list of NIST time servers
// http://tf.nist.gov/tf-cgi/servers.cgi
string[] servers = new string[] {
"nist1-ny.ustiming.org",
"nist1-nj.ustiming.org",
"nist1-pa.ustiming.org",
"time-a.nist.gov",
"time-b.nist.gov",
"nist1.aol-va.symmetricom.com",
"nist1.columbiacountyga.gov",
"nist1-chi.ustiming.org",
"nist.expertsmi.com",
"nist.netservicesgroup.com"
};
// Try 5 servers in random order to spread the load
Random rnd = new Random();
foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
{
try
{
// Connect to the server (at port 13) and get the response
string serverResponse = string.Empty;
using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
{
serverResponse = reader.ReadToEnd();
}
// If a response was received
if (!string.IsNullOrEmpty(serverResponse))
{
// Split the response string ("55596 11-02-14 13:54:11 00 0 0 478.1 UTC(NIST) *")
string[] tokens = serverResponse.Split(' ');
// Check the number of tokens
if (tokens.Length >= 6)
{
// Check the health status
string health = tokens[5];
if (health == "0")
{
// Get date and time parts from the server response
string[] dateParts = tokens[1].Split('-');
string[] timeParts = tokens[2].Split(':');
// Create a DateTime instance
DateTime utcDateTime = new DateTime(
Convert.ToInt32(dateParts[0]) + 2000,
Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
Convert.ToInt32(timeParts[2]));
// Convert received (UTC) DateTime value to the local timezone
result = utcDateTime.ToLocalTime();
return result;
// Response successfully received; exit the loop
}
}
}
}
catch
{
// Ignore exception and try the next server
}
}
return result;
}
编辑
var wc = GetFastestNISTDate();
var pattern = InstantPattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
var parseResult = pattern.Parse(wc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
if (!parseResult.Success)
throw new InvalidDataException("...whatever...");
var instant = parseResult.Value;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
var bclDateTime = zonedDateTime.ToDateTimeUnspecified();
时区转换不起作用。我从这个函数GetFastestNISTDate(); 得到了正确的日期,接下来我尝试根据我的第一个 UTC 时间获取不同时区的本地日期和时间,但代码返回伦敦的错误时间。我想我弄错了代码。任何人都可以看到并提供帮助。谢谢
【问题讨论】:
-
请注意
TimeZoneInfo类,可能会节省您的网络通话时间。