AronChan
AronChan

Reputation: 245

How do i display an variable from a switch statement on my ASP.NET page?

I'm trying to display the month from a datetime object in text so that it looks like this:

01 Dec 2011

I've created a switch statement to identify the month and put the string into a variable I want to display on my index.aspx page. However, it doesn't seem to work and I'm not sure why.

<% 
string month = "";
switch(item.postdate.Month)
{
    case(1):
        month = "Jan";
        break;

    case(2):
        month = "Feb";
        break;

    case(3):
        month = "Mar";
        break;

    case(4):
        month = "Apr";
        break;

    case(5):
        month = "Maj";
        break; 

    case(6):
        month = "jun";
        break;

    case(7):
        month = "Jul";
        break;

    case(8):
        month = "Aug";
        break;

    case(9):
        month = "Sep";
        break;

    case(10):
        month = "Okt";
        break; 

    case(11):
        month = "Nov";
        break; 

    case(12):
        month = "Dec";
        break;
};
Html.Display(month);
%>

Upvotes: 1

Views: 216

Answers (4)

Richard Friend
Richard Friend

Reputation: 16018

Whats wrong with just formatting the date how you want?

var dateAsString = item.postDate.ToString("MMM");

see here

Upvotes: 0

Anders
Anders

Reputation: 878

Can't you just use DateTime.ToString() Patterns?

You can read up on it here

Upvotes: -1

Dave Walker
Dave Walker

Reputation: 3523

Do you have a full datetime object?

If so you can use:

dateObject.ToString("dd MMM yyyy");

Upvotes: 3

GvS
GvS

Reputation: 52528

You could try:

<%: item.postdate.ToString("dd MMM yyyy") %>

Or if you just want the name in a string

string month = item.postdate.ToString("MMM") 

More information about DateTime.ToString()

Upvotes: 3

Related Questions