DateTime.Now.ToString("Y")
让我回复:2013年8月
上个月是否有一种简单的方法可以获得相同的格式?
类似于:DateTime.LastMonth.ToString("Y")
和输出将是:2013年7月
我知道这种方法不存在:)但也许还有其他东西可以实现输出?或者我需要为此创建自己的方法?
答案 0 :(得分:16)
答案 1 :(得分:9)
您可以使用DateTime.AddMonths()
var lastMonth = DateTime.Now.AddMonths(-1);
var lastMonthAsString = lastMonth.ToString("Y");
其他时间间隔也是如此,例如AddDays()
,AddSeconds()
或AddYears()
。您可以在MSDN's DateTime documentation找到所有可用的方法。
答案 2 :(得分:1)
使用扩展方法......也许就行了......
public static string LastMonth(this DateTime dt)
{
return DateTime.Now.AddMonths(-1).ToString("Y");
}
答案 3 :(得分:0)
如果您想获得缩写的月份名称,可以在以下行中
DateTime lastMonth = DateTime.Now.AddMonths(-1);
string Month = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(lastMonth.Month) ;