2010-10-29 79 views

回答

7

您可以試試:

編輯:

DateTime d; 
DateTime.TryParse("12/10/2010 00:00:00", d); 
d.ToString("MM/dd/yyyy"); 
+0

-1,我想你應該檢查你的代碼。 http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx – Codesleuth 2010-10-29 12:38:42

+0

@Codesleuth - Tru dat。冬天的代碼在早上打字。感謝名單。 – 2010-10-29 12:40:14

+0

很酷,刪除downvote :) – Codesleuth 2010-10-30 10:43:03

6

這需要你的字符串的前半部分的空間之前:

string formatedDt = "12/10/2010 00:00:00".Split(' ')[0]; 
+0

不能編譯,因爲string.Split是一個成員方法,而不是一個靜態函數。 – CodesInChaos 2010-10-29 13:07:10

+0

好的電話,我修好了。 – 2010-10-29 14:07:18

4
string s = "12/10/2010 00:00:00"; 
s = s.Substring(0,s.IndexOf(" "); 
+2

我認爲如果字符串中根本沒有空格,這個不起作用。 – CodesInChaos 2010-10-29 12:40:08

+0

@CodeInChaos - 如果沒有空間,這些解決方案都無法工作。爲什麼這個答案不同? – 2010-10-29 12:43:26

+0

如果輸入字符串不包含其中一個拆分字符,則String.Split會將整個字符串作爲[0]返回。 – CodesInChaos 2010-10-29 13:08:01

0
"12/10/2010 00:00:00".Split(' ')[0] 

這將返回整個字符串,如果它不包含空格。

或者,如果您需要在缺少空間的情況下,其他的行爲,你可以這樣做:

string s = "12/10/2010 00:00:00"; 
int spaceIndex=s.IndexOf(" "); 
if(spaceindex>=0) 
{ 
    return = s.Substring(0,spaceIndex); 
} 
else 
{ 
    //Handle the case without space here 
    //For example throw a descriptive exception 
    throw new InvalidDataException("String does not contain a space"); 
} 
+0

如果沒有空格,返回的字符串是「12/10/201000:00:00」,這不是OP想要的。 – 2010-10-29 13:07:40

+0

目前尚不清楚OP的要求。既返回整個字符串,從而使操作冪等並拋出一個描述性異常對我來說似乎是合理的。另一方面,拋出ArgumentOutOfRangeException異常對我來說似乎不合理。 – CodesInChaos 2010-10-29 13:19:43

+0

由於OP在示例輸入中給了空間,所以必須有一個空格。 – Dialecticus 2010-10-29 13:21:09