如何获得国家明智/时区明智的日期&时间来自互联网服务器 [英] How to get country wise / timezone wise date & time from internet server

查看:95
本文介绍了如何获得国家明智/时区明智的日期&时间来自互联网服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须显示日期&根据用户时区ID的时间。我不能依赖用户电脑的日期时间和设置。我在搜索Google,并获得了下面的代码。代码似乎会查询许多外部服务器的日期&时间,但有一件事不清楚我什么样的日期&时间我可以期待从下面的代码。



有些时候我需要印度时间。有一段时间我需要伦敦时间,有一段时间我需要其他国家当地时间。几个县有很多时区,这就是为什么我要发送时区id / name,并希望基于timezone id / name获取datetime。



所以只是指导我如何自定义下面的代码,我可以发送用户端的时区id和例程将返回正确的本地时间基于时区id,即使用户pc日期时间设置是错误的。寻找良好的帮助。感谢

  public static DateTime GetFastestNISTDate()
{
var result = DateTime.MinValue;

//初始化NIST时间服务器列表
// 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
};

//以随机顺序尝试5个服务器来传播加载
随机rnd = new Random();
foreach(服务器中的字符串服务器.OrderBy(s => rnd.NextDouble())。Take(5))
{
try
{
//连接到服务器(在端口13)并得到响应
string serverResponse = string.Empty;
using(var reader = new StreamReader(new System.Net.Sockets.TcpClient(server,13).GetStream()))
{
serverResponse = reader.ReadToEnd();
}

//如果收到响应
if(!string.IsNullOrEmpty(serverResponse))
{
//拆分响应字符串( 55596 11-02-14 13:54:11 00 0 0 478.1 UTC(NIST)*)
string [] tokens = serverResponse.Split('');

//检查令牌的数量
if(tokens.Length> = 6)
{
//检查运行状况
字符串的健康状况=令牌[5];
if(health ==0)
{
//从服务器响应获取日期和时间部分
string [] dateParts = tokens [1] .Split(' - ');
string [] timeParts = tokens [2] .Split(':');

//创建一个DateTime实例
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] ));

//将收到的(UTC)DateTime值转换为本地时区
result = utcDateTime.ToLocalTime();

返回结果;
//响应成功接收;退出循环

}
}

}

}
catch
{
/ /忽略异常并尝试下一个服务器
}
}
返回结果;
}



编辑



  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 =即时.InZone(timeZone);
var bclDateTime = zonedDateTime.ToDateTimeUnspecified();

时区翻译不起作用。我从这个函数获得正确的日期 GetFastestNISTDate(); 然后我尝试根据我的第一个utc时间获取不同时区的本地日期和时间,但是代码返回错误的时间伦敦。我想我错了代码。任何人都可以看到&帮帮我。谢谢

解决方案

时间服务器将报告UTC时间(这就是为什么变量名为 utcDateTime )。



result = utcDateTime.ToLocalTime(); 将UTC时间从时间服务器转换为本地时间到您计算机所在的时区。如果您想要一个不同的时区,则需要更改该行。



如上所述,您可以使用 TimeZoneInfo.ConvertTimeFromUtc 转换为某个指定的时区。请参见该页面上的示例。

  TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById(Central Standard Time); 
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc,cstZone);


i have to show date & time to user as per the user timezone id. i can not rely on user pc date time and setting. i was searching Google for the way and got a below code. code seems will query many external server for date & time but one thing not clear to me what kind of date & time i can expect from the below code.

some time i need india time. some time i need london time and some time i need other country local time. few county has many timezone that is why i want to send timezone id/name and want to get datetime based on timezone id/name.

so just guide me how to customize the below code where i can send user's side timezone id and routine will return right local time based on timezone id even if user pc datetime setting is wrong. looking for good help. thanks

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;
    }

EDIT

    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();

timezone translation is not working. i got the right date from this function GetFastestNISTDate(); and next i try to get local date and time of different timezone based on my first utc time but code return wrong time for London. i guess i am making mistake the code. can anyone see & help. thanks

解决方案

The timeservers will report UTC time (that's why the variable is named utcDateTime).

The result = utcDateTime.ToLocalTime(); line converts that UTC time from the timeserver to the local time according to the timezone your computer is in. If you want a different timezone, you need to change that line.

As amit mentioned, you can use TimeZoneInfo.ConvertTimeFromUtc to convert to some specified timezone. See the example on that page.

TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);

这篇关于如何获得国家明智/时区明智的日期&时间来自互联网服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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