将时区信息转换为日期时间

时间:2011-11-07 17:23:18

标签: c#

如何将包含时区指定的以下日期时间字符串转换为日期时间类型?

这是字符串“2011-11-27 23:59:59 EST”

这是我在msdn上发现的:

class Program
{
    static void Main(string[] args)
    {
        // I realize here that the types don't match but just trying to
        // illustrate what i'm trying to do
        DateTime myDate = ReturnTimeOnServer("2011-11-27 23:59:59 EST");
    }

    public static DateTimeOffset ReturnTimeOnServer(string clientString)
    {
        string format = @"yyyy-mm-dd h:m:s zzz";
        TimeSpan serverOffset = TimeZoneInfo.Local.GetUtcOffset(DateTimeOffset.Now);

        try
        {
            DateTimeOffset clientTime = DateTimeOffset.ParseExact(clientString, format, CultureInfo.InvariantCulture);
            DateTimeOffset serverTime = clientTime.ToOffset(serverOffset);
            return serverTime;
        }
        catch (FormatException)
        {
            return DateTimeOffset.MinValue;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

var myDate = DateTime.ParseExact("2011-11-27 23:59:59 EST", 
    "yyyy-MM-dd HH:mm:ss EST", CultureInfo.InvariantCulture);