Mark
Mark

Reputation: 31

DateTime getting todays Month in if statement

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

Upvotes: 2

Views: 5547

Answers (11)

Ankit
Ankit

Reputation: 6664

Make an enum for Month and use this case statement

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

Upvotes: 0

temarsden
temarsden

Reputation: 332

You can use DateTime.Now.Month

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

Upvotes: 0

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

Upvotes: 2

Vismari
Vismari

Reputation: 745

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

Upvotes: 0

Chris Trombley
Chris Trombley

Reputation: 2322

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

Upvotes: 3

Russell Troywest
Russell Troywest

Reputation: 8776

Use the DateTime.Month property to check month

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

Upvotes: 1

mellamokb
mellamokb

Reputation: 56779

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.
}

Upvotes: 0

Jason Yost
Jason Yost

Reputation: 4947

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

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 161002

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

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

Upvotes: 8

Bob
Bob

Reputation: 99824

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

Upvotes: 1

Related Questions