/ 文档备忘 / 0浏览

ASP.NET C# 本地时间与GMT(UTC)标准时间之间的互相转换(转)

    /// <summary>   
    /// 本地时间转成GMT(UTC)时间   
    /// </summary>   
    public static string ToGMTString(DateTime dt)  
    {  
        return dt.ToUniversalTime().ToString("r");  
    }

    /// <summary>   
    /// 本地时间转成GMT(UTC)格式的时间   
    /// </summary>   
    public static string ToGMTFormat(DateTime dt)
    {
        return dt.ToString("r") + dt.ToString("zzz").Replace(":", "");
    }

    /// <summary>   
    /// GMT时间转成本地时间   
    /// </summary>   
    /// <param name="gmt">字符串形式的GMT时间</param>   
    /// <returns></returns>   
    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
        {
        }
        return dt;
    }