C#获取北京时间

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static DateTime GMT2Local(string gmt)
{
DateTime dt = DateTime.MinValue;
try
{
string pattern = "";
if (gmt.IndexOf("+0") != -1)
{
gmt = gmt.Replace("GMT", "");
pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
}
if (gmt.ToUpper().IndexOf("GMT") != -1)
{
pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
}
if (pattern != "")
{
dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
dt = dt.ToLocalTime();
}
else
{
dt = Convert.ToDateTime(gmt);
}
}
catch (Exception ex)
{

}
return dt;
}


public static DateTime GetNetDateTime()
{
WebRequest request = null;
WebResponse response = null;
WebHeaderCollection headerCollection = null;
string datetimeStr = string.Empty;
DateTime dt = DateTime.Now;
try
{
request = WebRequest.Create("http://www.baidu.com");
request.Timeout = 500;
request.Credentials = CredentialCache.DefaultCredentials;
response = (WebResponse)request.GetResponse();
headerCollection = response.Headers;
foreach (var h in headerCollection.AllKeys)
{
if (h == "Date")
{
datetimeStr = headerCollection[h];
dt = GMT2Local(datetimeStr);
}
}
return dt;
}
catch (Exception)
{
return dt;
}
finally
{
if (request != null)
{ request.Abort(); }
if (response != null)
{ response.Close(); }
if (headerCollection != null)
{ headerCollection.Clear(); }
}
}
private void button1_Click(object sender, EventArgs e)
{
DateTime dt1 = GetNetDateTime();
MessageBox.Show(dt1.ToString());

}
}
}

posted on 2022-02-18 09:36  岁月寒风  阅读(726)  评论(0编辑  收藏  举报

导航