views:

484

answers:

2

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

+4  A: 

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());
Bob
As I understand author means format string for full line, i.e. for 'January 11th, "111"'.
arbiter
I agree with you. Thats why actual implementation is parsing it manually. I was just wondering if there was DateTime property
grobartn
Good to hear. Also, if you use the manual parsing method I provided, you may want to add additional validation, ie check for zero date, check to see if value > 100 (101 is min date for that format)
Bob
+1  A: 

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