using System.Net;
using System.IO;
using System.Text.RegularExpressions;
//获取中国标准时间(由美国官方时间折算)
private void GetNistTimeCN(out string time, out string Data)
{
try
{
//nist.time.gov的url
string strNistUrl = "http://nist.time.gov/timezone.cgi?UTC/s/0";
//构造并实例化一个WebRequest
System.Net.WebRequest myHttpWebRequest = System.Net.HttpWebRequest.Create(strNistUrl);
//设置连接超时时间
myHttpWebRequest.Timeout = 8000;
//设置WebResponse,接收返回信息
System.Net.WebResponse myHttpWebResponse = myHttpWebRequest.GetResponse();
//获取返回信息流信息
Stream sr = myHttpWebResponse.GetResponseStream();
//设置流阅读器
StreamReader reader = new StreamReader(sr, System.Text.Encoding.ASCII);
//流输出为字符串
String srdata = reader.ReadToEnd();
//将返回html文本中的双引号变为单引号
srdata = srdata.Replace("/"", "/'");
//用模式匹配加分割的方式定位和获取时间信息
string strOut = Regex.Split(srdata, "color='white'><b>", RegexOptions.IgnoreCase)[1];
string strTime = Regex.Split(strOut, "<br>", RegexOptions.IgnoreCase)[0];
//小时需调整,因时区相差8小时
time = DateTime.Parse(strTime).AddHours(8).ToLongTimeString();
//用模式匹配加分割的方式定位和获取日期信息
string strOut1 = Regex.Split(srdata, "'5' color='white'>", RegexOptions.IgnoreCase)[1];
string strData = Regex.Split(strOut1, "<br>", RegexOptions.IgnoreCase)[0];
//获取中国时间-小时部分
int intHourCn = int.Parse(time.Split(':')[0]);
//获取美国时间-小时部分
int intHourUS = int.Parse(DateTime.Parse(strTime).ToLongTimeString().Split(':')[0]);
//比较小时差异,调整日期差异
if (intHourCn < intHourUS)
{
Data = DateTime.Parse(strData).AddDays(1).ToShortDateString();
}
else
{
Data = DateTime.Parse(strData).ToShortDateString();
}
}
catch (System.Exception ex)
{
time = string.Empty;
Data = string.Empty;
throw ex;
}
}
private void SetDateTime()
{
try
{
string strTime = string.Empty;
string strDate = string.Empty;
GetNistTimeCN(out strTime, out strDate);
// 设置标准时间
standTime.Text = strDate + " " +strTime;
// 设置系统时间
systemTime.Text = DateTime.Now.ToString();
}
catch (System.Exception ex)
{
throw ex;
}
}