grobartn
grobartn

Reputation: 3590

Parse month and date from string DateTime

Lets say you have strings of this format.

January 11th, "111" November 1st, "1101" October 13th, "1013" etc.

So basically all you want to parse it and store in two variables date and month.

I do not need code for parsing, I can easily do that. I was just wondering if someone knows the way to do it using something like DateTime.TryParse() or something similiar.

Cheers

Upvotes: 3

Views: 4265

Answers (2)

Bob
Bob

Reputation: 99824

Using DateTime it might be something like this

string value = "111";
if (value.Length < 4) value = "0" + value;
DateTime dt;
if (DateTime.TryParseExact(value, "MMdd", 
     CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) {
    int month = dt.Month;
    int day = dt.Day;
}

But in all honesty, you are better off just parsing the string manually. If you want the day and month part in two separate variables you are just introducing overhead (as small as it might be) with DateTime that you don't need.

int value = 111;
int month = value / 100;
int day = value % 100;

if (month > 12)
    throw new Exception("Invalid Month " + month.ToString());

if (day > DateTime.DaysInMonth(year, month))
    throw new Exception("Invalid Day " + day.ToString());

Upvotes: 6

bdukes
bdukes

Reputation: 156055

You should be able to do that using ParseExact or TryParseExact.

I don't think your example is going to work, it refuses to parse 111 as January 11, seeing it as October 1. If you stick with two digits for both parts of the date, that should be cleaner.

DateTime parsedDate;
if (DateTime.TryParseExact("0111", "MMdd", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
    // do something with parsedDate.Month and parsedDate.Day
}

Upvotes: 1

Related Questions