DateTime在if语句中获得今天的月份

时间:2011-04-29 19:06:07

标签: c#

我想在月份== 1月份做一个if语句,例如加载一些东西 否则如果月份==四月加载别的东西。 请有人帮忙吗 感谢

11 个答案:

答案 0 :(得分:8)

您可以使用Month属性,范围是1-12:

int month = DateTime.Now.Month;
if(month == 4) //April
{..

答案 1 :(得分:2)

有两种方式

if(DateTime.Today.Month == 1){
  // do something
}

if(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month) == "January"){
  // do something
}

对于第二种方法,您需要包含System.Globalization

答案 2 :(得分:2)

switch (DateTime.Now.Month)
{
     case 1: // JAN
        ...
        break;
     case 2: // FEB
        ...
        break;
}

答案 3 :(得分:2)

您可以像这样创建一年中包含月份的枚举:

public enum Months{
     January = 1,
     February = 2,
     .
     .
     December = 12
}

然后尝试

if(Datetime.Now.Month == (int)Months.January){

  //Do Something...

} else if(Datetime.Now.Month == (int)Months.April){

  //Do Something else

}

希望这会有所帮助。的问候,

Juan Alvarez

答案 4 :(得分:1)

var now = DateTime.Now;
var monthName = now.ToString("MMMM")
if (monthName == "January)
{
  //load something 
}
else if (monthName == "April")
{
  //load something else. 
}

答案 5 :(得分:1)

使用DateTime.Month属性检查月份

switch (DateTime.Now.Month){
  case 1://January stuff here
  break;
  case 2://Feb stuff here etc...
}

答案 6 :(得分:0)

请参阅Is there a predefined enumeration for Month in the .NET library?

string monthName = CultureInfo.CurrentCulture.DateTimeFormat
    .GetMonth ( DateTime.Now.Month );

switch (monthName)
{
    case "January":
        // do something
        break;
    case "April":
        // do something
        break;
    // etc.
}

答案 7 :(得分:0)

答案 8 :(得分:0)

string monthName = DateTime.Now.ToString("MMMM");
if(monthName == "april"{
...
}

答案 9 :(得分:0)

您可以使用DateTime.Now.Month

        if(DateTime.Now.Month == 1)
        {
            //January
        }
        else if (DateTime.Now.Month == 2)
        {
            //February
        }
        //etc

答案 10 :(得分:0)

为月份制作一个枚举并使用此案例陈述

switch (DateTime.Now.Month)
{
     case MonthEnum.JAN
        break;
}