C#获取获取北京时间多种方法

///<summary>
/// 获取标准北京时间
///</summary>
///<returns></returns>
public static DateTime GetBeijingTime()
{
    //t0 = new Date().getTime();
    //nyear = 2011;
    //nmonth = 7;
    //nday = 5;
    //nwday = 2;
    //nhrs = 17;
    //nmin = 12;
    //nsec = 12;
    DateTime dt;
    WebRequest wrt = null;
    WebResponse wrp = null;
    try
    {
        wrt = WebRequest.Create("http://www.beijing-time.org/time.asp");
        wrp = wrt.GetResponse();

        string html = string.Empty;
        using (Stream stream = wrp.GetResponseStream())
        {
            using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
            {
                html = sr.ReadToEnd();
            }
        }

        string[] tempArray = html.Split(';');
        for (int i = 0; i < tempArray.Length; i++)
        {
            tempArray[i] = tempArray[i].Replace("\r\n", "");
        }

        string year = tempArray[1].Substring(tempArray[1].IndexOf("nyear=") + 6);
        string month = tempArray[2].Substring(tempArray[2].IndexOf("nmonth=") + 7);
        string day = tempArray[3].Substring(tempArray[3].IndexOf("nday=") + 5);
        string hour = tempArray[5].Substring(tempArray[5].IndexOf("nhrs=") + 5);
        string minite = tempArray[6].Substring(tempArray[6].IndexOf("nmin=") + 5);
        string second = tempArray[7].Substring(tempArray[7].IndexOf("nsec=") + 5);
        dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second);
    }
    catch (WebException)
    {
        return DateTime.Parse("2011-1-1");
    }
    catch (Exception)
    {
        return DateTime.Parse("2011-1-1");
    }
    finally
    {
        if (wrp != null)
            wrp.Close();
        if (wrt != null)
            wrt.Abort();
    }
    return dt;
}
posted @ 2011-07-17 21:02  事理  阅读(9548)  评论(1编辑  收藏  举报