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

标签 c# datetime parsing

假设您有这种格式的字符串。

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/

相关文章:

python - 将日期作为 URL 参数传递给 flask 路由

php - 在 PHP 上解析 JSON 并提取特定值

ruby - 为什么 "23 Dogs"在 pry 中被解析为 2015 年 11 月 23 日,但 "3 Dogs"给出解析器错误?

c++ - C++中的电子邮件解析器

c# - 转换空字符引用 ToString()

c# - 如何使用 LINQ 解析此 XML?

jquery - 如何在 jQuery 中将 DateTime 值转换为 dd/mm/yyyy?

javascript - SignalR 错误 : signalR(. ..).starting(...).sending 不是函数

c# - 安装自研Windows Service

c# - 使用当前日期创建文件名