2013-01-10 16 views
9

我用下面的函數DateTime轉換從/爲string如何最新與「T」到/轉換從字符串在C#中

DATE_OBJ.ToString(DATE_FORMAT); 

DateTime.ParseExact(Date_string, DATE_FORMAT, null); 

現在我已經得到了與後續格式工作2012-03-20T14:18:25.000+04:00

我應該使用哪種格式將其正確地轉換爲string,並生成string,就像DateTime對象那樣?

+0

請到通過這[鏈接](http://www.w3.org/TR/NOTE-datetime)。它可以幫助你 –

回答

11

你可以從DateTime轉到該格式

DateTime dt = new DateTime(); 
dt.Tostring("o"); 

,並從該格式的日期時間與

DateTimeOffset.Parse(dateString); 

這裏是DateTime格式一些更多的信息: http://www.dotnetperls.com/datetime-format

+1

+1:但是,我建議閱讀MSDN [往返(「O」,「o」)格式說明符](http:// msdn.microsoft.com/en-us/library/az4se3k1.aspx#Roundtrip) – horgh

+0

這是一個很好的鏈接。謝謝@KonstantinVasilcov – Moriya

-3

如果這是一個您接收到的字符串,那麼您可以通過T分割字符串,並僅使用整個字符串的Date組件的第一部分並解析該字符串。

例如:

string dateTimeAsString = "2012-03-20T14:18:25.000+04:00"; 
string dateComponent = dateTimeAsString.Splic('T')[0]; 
DateTime date = DateTime.ParseExact(dateComponent, "yyyy-MM-dd",null); 
+0

問題是相反的:DateTime - >字符串 – Jacco

2

你不能從DateTime做到這一點,因爲DateTime沒有保持TimeZone信息。

這是關閉:string.Format("{0:s}", dt)將給2012-03-20T14:18:25。 請參閱:http://www.csharp-examples.net/string-format-datetime/

你可以此擴大到:string.Format("{0:s}.{0:fff}", dt),這將給2012-03-20T14:18:25.000

但你最好看看DateTimeOffsetDateTime vs DateTimeOffset

(不可取的,但假的,並仍然使用DateTimestring.Format("{0:s}.{0:fff}+04:00", dt)

5

您使用DateTimeOffSet喜歡的更好:

string str = " 2012-03-20T14:18:25.000+04:00"; 
DateTimeOffset dto = DateTimeOffset.Parse(str); 
//Get the date object from the string. 
DateTime dtObject = dto.DateTime; 

//Convert the DateTimeOffSet to string. 
string newVal = dto.ToString("o");