2010-06-11 47 views
7

有沒有簡單的方法將簡單數字(包括軍隊時間)轉換爲時間格式(上午,下午格式)?我可以做繁瑣的做法,但我只是想知道是否有另一種方式將數字轉換爲時間?

0800 => 8:00

2317 =>下午11時17

+0

「繁瑣的方法」是什麼意思? DateTime.ParseExact()與自定義格式提供程序? – Odrade 2010-06-11 13:46:41

+1

var time = DateTime.ParseExact(「0800」,「HHmm」,CultureInfo.InvariantCulture); – 2010-06-11 13:51:49

回答

12
DateTime dt = DateTime.ParseExact("0800", "HHmm", CultureInfo.InvariantCulture); 
    string timestring = dt.ToString("h:mm tt"); 

對於格式代碼,請參見documentation

1

希望這點你在正確的方向:

string time = "0800"; 
    DateTime dt = DateTime.ParseExact(string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2)), "HH:mm", CultureInfo.InvariantCulture); 
    MessageBox.Show(string.Format("{0:h:mm tt}", dt)); 

    time = "2345"; 
    dt = DateTime.ParseExact(string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2)), "HH:mm", CultureInfo.InvariantCulture); 
    MessageBox.Show(string.Format("{0:h:mm tt}", dt)); 
+0

爲什麼你將字符串重新格式化爲HH:mm格式而不是用戶直接HHmm格式? – 2010-06-11 13:52:28

+0

好問題。因爲我寫得很快,並沒有考慮到這一點。 :) – Robaticus 2010-06-11 14:10:02

+0

@Robaticus如果輸入時間是「23」(如00:23),該怎麼辦?然後你的代碼會拋出異常。 – 2014-03-07 11:04:11

1

使用DateTime.TryParse與您想要的格式字符串。

如果您可以接受多種格式,那麼您需要依次調用每個格式,直到找到匹配的格式爲止 - 我認爲這是您「繁瑣的方法」所表達的意思。