2012-12-15 141 views
2

可能重複:
Date time format from string?將字符串轉換爲DateTime

有誰知道我怎麼能下列字符串轉換爲C#中的DateTime價值?

"Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)" 
+0

也期待http://stackoverflow.com/questions/919244/converting-string- to-datetime-c-net –

+0

@Bhushan Firake。我已經嘗試過DateTime.ParseExact(字符串,格式,格式提供程序),但是我應該使用什麼格式以上 – lafama

+1

@lafama:您可以閱讀本文http://www.codeproject.com/Articles/14743/Easy-String日期時間 - 日期時間 - 字符串 - 和 - 對於 –

回答

6

如果你僅僅使用"GMT+0300 (E. Africa Standard Time)"結尾的字符串,你可以嘗試:是

string dateString = "Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)"; 
DateTime date = DateTime.ParseExact(dateString, "ddd MMM dd yyyy HH:mm:ss 'GMT+0300 (E. Africa Standard Time)'", System.Globalization.CultureInfo.InvariantCulture); 

的說明符的含義如下:

  • 「ddd」縮寫名稱o星期幾。
  • 「MMM」月份的縮寫名稱。
  • 「dd」月的日期,從01到31.
  • 「yyyy」年份爲四位數字。
  • 「HH」的小時,通過59
  • 使用從00 24小時時鐘從00到59
  • 「SS」的第二個,從00到23
  • 「毫米」的那一刻, 「
  • 」:「時間分隔符。
  • 「string」,「string」文字字符串分隔符。

你可以找到更多關於命名Custom Date and Time Format Strings

而且,如果你想太多解析"GMT+0300 (E. Africa Standard Time)"部分MSDN文章在不同的格式說明,我想你應該執行的方式給自己解析。我不認爲這是一個說明者。

+1

原則上你的指定符列表還應該提及:?'':''你使用的格式提供者的'TimeSeparator';將轉化爲不變文化的':'。翻譯成其他文化的「。」。 –

+0

@傑普:你說得對,我忘了那個。現在添加它。 – hattenn

0

試試這個:

DateTime date = DateTime.Parse(yourDateTimeString); 
+0

對不起。這是行不通的 – lafama

1

首先,你應該爲你的非洲標準時間文化信息使用';

CultureInfo("af-ZA", false); 

但是你的字符串轉換爲DateTime真的很複雜。對我來說,看起來不可能完美轉換爲DateTime。但我們可以在你的絃樂中進行一些修復。例如,如果你的字符串是這樣的; "11/15/2012 00:00:00"你可以像這樣轉換它;

using System; 
using System.Globalization; 

namespace Programs 
{ 
    public class Program 
    {  
     public static void Main(string[] args) 
     { 
      string str = "11/15/2012 00:00:00"; 
      DateTime dt = DateTime.ParseExact(str, "MM/dd/yyyy hh:mm:ss", new CultureInfo("af-ZA")); 
      Console.WriteLine(dt.ToString()); 
     } 
    } 
} 

Custom Date and Time Format Strings

​​

0

有沒有辦法來處理(E.非洲標準時間)。

假設UTC = GMT還可以得到時區的一部分,只是刪除不是你的字符串的重要組成部分

string t = Regex.Replace("Thu Nov 15 2012 00:00:00 GMT+0300 (E. Africa Standard Time)", "([(].+?[)])", ""); 
t= t.Replace("GMT", "").Trim(); 

DateTime a = DateTime.ParseExact(t, "ddd MMM dd yyyy HH:mm:ss zzzz", System.Globalization.CultureInfo.InvariantCulture);