2013-08-01 36 views
5

DateTime.Now.ToString("Y")方法返回我:2013有沒有拿到上個月的名字和年份在C#

八月有一個簡單的方法,上個月得到相同的格式?

喜歡的東西:DateTime.LastMonth.ToString("Y")輸出將是:7月2013

我知道這個方法存在犯規:)但也許還有別的東西來實現這一目標的輸出?或者我需要爲此創建自己的方法?通過使用DateTime.AddMonths()

var lastMonth = DateTime.Now.AddMonths(-1); 
var lastMonthAsString = lastMonth.ToString("Y"); 

同樣存在其他時間間隔像

var lastMonth = DateTime.Now.AddMonths(-1).ToString("Y");` 

回答

16

爲什麼不使用DateTime.AddMonths

例如AddDays()AddSeconds()AddYears()。你可以在MSDN's DateTime documentation找到所有可用的方法。

+0

它似乎是DateTime的靜態方法? – akd

+1

得到它我應該使用現在也:) :) – akd

+0

非常感謝你:) – akd

9

您可以從某一特定日期加上或減去月:

1

使用擴展方法...沿線或許真的......

public static string LastMonth(this DateTime dt) 
{ 
return DateTime.Now.AddMonths(-1).ToString("Y"); 
} 
0

如果你想獲得縮寫月份名稱,可以在下面的線條,

DateTime lastMonth = DateTime.Now.AddMonths(-1); 
string Month =  CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(lastMonth.Month) ;