【问题标题】:Best way to get the current month number in C#在 C# 中获取当前月份数的最佳方法
【发布时间】:2012-01-08 12:57:08
【问题描述】:

我正在使用 C# 获取当前月份数:

string k=DateTime.Now.Month.ToString();

一月份它会返回1,但我需要得到01。如果 12 月是当前月份,我需要获取 12。在 C# 中获得此功能的最佳方法是什么?

【问题讨论】:

    标签: c# string datetime


    【解决方案1】:
    string sMonth = DateTime.Now.ToString("MM");
    

    【讨论】:

    • 如果我们需要获得其他月份的 MM 怎么办?
    • @AlokRajasukumaran someDate.ToString("MM yyyy")
    【解决方案2】:

    有很多不同的方法。

    为了保持语义,我将使用DateTimeMonth 属性并使用custom numeric format strings 之一进行格式化:

    DateTime.Now.Month.ToString("00");
    

    【讨论】:

      【解决方案3】:
          using System;
      
      class Program
      {
          static void Main()
          {
          //
          // Get the current month integer.
          //
          DateTime now = DateTime.Now;
          //
          // Write the month integer and then the three-letter month.
          //
          Console.WriteLine(now.Month);
          Console.WriteLine(now.ToString("MMM"));
          }
      }
      

      输出

      5

      五月

      【讨论】:

        【解决方案4】:
        DateTime.Now.Month.ToString("0#")
        

        【讨论】:

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