假设您有这种格式的字符串。
1月11日,“111” 11月1日《1101》 10月13日《1013》 等等
所以基本上你想要解析它并存储在两个变量日期和月份中。
我不需要解析代码,我可以轻松做到这一点。 我只是想知道是否有人知道如何使用类似的东西来做到这一点 DateTime.TryParse() 或类似的东西。
干杯
最佳答案
使用 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;
}
但老实说,您最好手动解析字符串。如果您希望将日期和月份部分放在两个单独的变量中,那么您只是引入了不需要的 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());
关于c# - 从字符串 DateTime 中解析月份和日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1059554/