Parse month and date from string DateTime
c#, datetime, parsing
Solution
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());
Problem
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