2013-12-18 35 views

回答

3

您可以使用TryParseExact

class Program 
{ 
    static void Main(string[] args) 
    { 
     var dtString = "Tue Mar 13 12:00:00 EST 2012".ConvertTimeZone(); 
     DateTime dt; 
     var success = DateTime.TryParseExact(
      dtString, 
      "ddd MMM dd HH:mm:ss zzz yyyy", 
      CultureInfo.InvariantCulture, 
      DateTimeStyles.None, 
      out dt); 

     Console.WriteLine(success); 
     if (Debugger.IsAttached) { Console.ReadKey(); } 
    } 
} 

public static class Extensions 
{ 
    private static Dictionary<string, string> _timeZones = 
     new Dictionary<string, string> { { "EST", "-05:00" } }; 

    public static string ConvertTimeZone(this string s) 
    { 
     var tz = s.Substring(20, 3); 
     return s.Replace(tz, _timeZones[tz]); 
    } 
} 

如果轉換成功,successtruedt將有日期和時間值。

好吧,讓我們來談談這個問題。實際上,我必須進行潛水並承諾將時區實際轉換爲偏移量。這非常準確,但需要一些維護。唯一需要維護的是Dictionary<string, string> _timeZones。您需要添加您想要支持的所有時區。

+0

我試過'dateValue =「Tue Mar 13 12:00:00 EST 2012」;'而且它不起作用。 – enb081

+0

@ enb081,月份的那天是「13」嗎? –

+0

是的,它實際上是一個月中的某一天。當我做'Response.Write(成功)'我得到'false'。 – enb081

0

DateTime.ParseExact。例如爲 「2009-05-08 14:40:52531」:

DateTime date = DateTime.ParseExact(
        "2009-05-08 14:40:52,531", 
        "yyyy-MM-dd HH:mm:ss,fff", 
        System.Globalization.CultureInfo.InvariantCulture); 

而對於你的情況格式應該是這樣的: 「DDD MMM DD HH:MM:SS ZZZ YYYY」:

DateTime date = DateTime.ParseExact(
        "Tue Mar 13 12:00:00 EST 2012", 
        "ddd MMM dd HH:mm:ss zzz yyyy", 
        System.Globalization.CultureInfo.InvariantCulture); 

問題在於獲取時區。 Kzzz格式化選項返回數字時差,例如+02:00但您需要使用字母。可能的解決方案是創建輔助方法,將時間偏移轉換爲字母表示。不幸的是,我沒有看到任何其他合理的選擇讓這件事情起作用。

​​
+0

我收到異常'字符串未被識別爲有效的DateTime.' – enb081

+0

@ enb081更新。 –

+0

仍然是例外。 – enb081

相關問題