2013-02-13 161 views
-3
 //This will get the month as an int (e.g. 4) 
     DateTime dLastMonth = DateTime.Today.AddMonths(-1); 
     int iLastMonth = dLastMonth.Year; 

我怎樣才能讓上面的代碼輸出01,02,等等,而不是1,2,3 ...如何格式化日期?

+0

你試過谷歌? 「c#datetime格式」的第一個命中是http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx – 2013-02-13 14:52:24

+0

如果你想格式化整個日期,爲什麼你只提取年份? – 2013-02-13 14:52:31

+1

我想他認爲如果這個月是一月份,刪除一個月,那麼這一年會是什麼樣子......瘋狂的猜測。 – 2013-02-13 14:55:55

回答

2

我對你的問題感到困惑,但如果你想進行格式化轉換成字符串(01,02,03等)使用方法:

var formatted = iLastMonth.ToString("D2") 
Console.WriteLine(formatted);