2010-08-21 123 views
4
Literal four = new Literal(); 
    string timeanddate; 
    timeanddate = DateTime.UtcNow.ToString(); 
    DateTime dt = new DateTime(); 
    DateTime dt_calc = new DateTime(); 
    dt = Convert.ToDateTime(timeanddate); 
    dt_calc = dt.AddHours(3); 
    four.Text = "3hr added and this gives>> " + dt_calc.ToString(); 
    form1.Controls.Add(four); 

一切都在上午下午我要工作24小時與如何將時間格式更改爲24小時?在C#中

回答

9

對你可能希望格式化DateTime各種方式見this page

請注意,您在24小時內使用「HH」。

例如,如果你想要的格式爲「23:00:00」,而不是「下午11時00分○○秒」你會用:

string formatted = dt_calc.ToString("HH:mm:ss"); 

順便說一句,你的初始化你DateTime值與new DateTime()是不必要的。

+0

不錯,但,是有辦法,使24小時默認,這就是如果我DONOT要使用的任何格式選項!只是默認返回的值應該是24小時。 – user287745 2010-08-21 07:56:45

+0

@ user287745:是的,有!首先看[jgauffin的答案](http://stackoverflow.com/questions/3536789/how-to-change-time-format-to-24hrs-in-c/3537366#3537366);那麼有關更多信息,請參閱:[CurrentCulture](http://msdn.microsoft.com/zh-cn/library/system.globalization.cultureinfo.currentculture.aspx)和[DateTimeFormatInfo](http:///msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx)。 – 2010-08-21 14:43:01

2

你必須改變當前的文化。

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(1053); 
string swedishTime = DateTime.Now.ToShortTimeString(); //24h format 

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(1033); 
string englishTime = DateTime.Now.ToShortTimeString(); //am/pm format 
0
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern = "HH:mm:ss" 
+0

雖然這段代碼可能會解決這個問題,但[包括一個解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! – kayess 2017-07-13 13:14:05

相關問題