2

I want to do an if statement if month == january for example load something else if month == april load something else. Can someone help please Thanks

Mark
  • 31
  • 1
  • 2

11 Answers11

8

You can use the Month property, range is 1-12:

int month = DateTime.Now.Month;
if(month == 4) //April
{..
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
3
switch (DateTime.Now.Month)
{
     case 1: // JAN
        ...
        break;
     case 2: // FEB
        ...
        break;
}
Chris Trombley
  • 2,232
  • 1
  • 17
  • 24
2

A couple of ways

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

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

for the second method you will need to include System.Globalization

Jason Yost
  • 4,807
  • 7
  • 42
  • 65
2

You can create an Enum with the Months of the year like this:

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

And try

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

  //Do Something...

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

  //Do Something else

}

Hope this helps. Regards,

Juan Alvarez

1
var now = DateTime.Now;
var monthName = now.ToString("MMMM")
if (monthName == "January)
{
  //load something 
}
else if (monthName == "April")
{
  //load something else. 
}
Bob
  • 97,670
  • 29
  • 122
  • 130
1

Use the DateTime.Month property to check month

switch (DateTime.Now.Month){
  case 1://January stuff here
  break;
  case 2://Feb stuff here etc...
}
Russell Troywest
  • 8,635
  • 3
  • 35
  • 40
0

See 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.
}
Community
  • 1
  • 1
mellamokb
  • 56,094
  • 12
  • 110
  • 136
0

These should help -

http://www.dotnetperls.com/datetime-month

Get the previous month's first and last day dates in c#

Community
  • 1
  • 1
IrishChieftain
  • 15,108
  • 7
  • 50
  • 91
0
string monthName = DateTime.Now.ToString("MMMM");
if(monthName == "april"{
...
}
Vismari
  • 745
  • 3
  • 12
0

You can use DateTime.Now.Month

        if(DateTime.Now.Month == 1)
        {
            //January
        }
        else if (DateTime.Now.Month == 2)
        {
            //February
        }
        //etc
temarsden
  • 332
  • 5
  • 16
0

Make an enum for Month and use this case statement

switch (DateTime.Now.Month)
{
     case MonthEnum.JAN
        break;
}
Ankit
  • 6,388
  • 8
  • 54
  • 79