【问题标题】:Is there a method to get last month name and year in C#有没有办法在 C# 中获取上个月的名称和年份
【发布时间】:2013-08-02 14:47:51
【问题描述】:

DateTime.Now.ToString("Y") 回复我:2013 年 8 月

有没有一种简单的方法可以以相同的格式获取上个月的内容?

类似:DateTime.LastMonth.ToString("Y"),输出将是:2013 年 7 月

我知道这种方法不存在 :) 但也许还有其他方法可以实现该输出?或者我需要为此创建自己的方法?

【问题讨论】:

    标签: c# .net date datetime


    【解决方案1】:

    为什么不使用DateTime.AddMonths

    例如:

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

    【讨论】:

    • 好像不是DateTime的静态方法?
    • 得到它,我现在也应该使用 :)
    • 正确,它不是静态方法,它仅适用于实例化的 DateTime,这就是 DateTime.Now 返回的内容。
    • @akdurmus - 没问题 :)
    【解决方案2】:

    您可以使用DateTime.AddMonths()从给定日期增加或减少月份

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

    AddDays()AddSeconds()AddYears() 等其他时间间隔也是如此。你可以在MSDN's DateTime documentation找到所有可用的方法。

    【讨论】:

      【解决方案3】:

      使用扩展方法...也许是类似的东西...

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

      【讨论】:

        【解决方案4】:

        如果你想得到缩写的月份名称,你可以在下面的行中,

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多