从字符串DateTime中解析月份和日期

gro*_*rtn 2 c# datetime parsing

假设你有这种格式的字符串.

1月11日,"111"11月1日,"1101"10月13日,"1013"等

所以基本上所有你想解析它并存储在两个变量日期和月份.

我不需要解析代码,我可以很容易地做到这一点.我只是想知道是否有人知道使用类似DateTime.TryParse()或类似的东西的方法.

干杯

Bob*_*Bob 5

使用DateTime可能是这样的

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;
}
Run Code Online (Sandbox Code Playgroud)

但说实话,你最好只手动解析字符串.如果您希望将日期和月份分成两个单独的变量,那么您只需要使用不需要的DateTime来引入开销(尽可能小).

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());
Run Code Online (Sandbox Code Playgroud)