c# - DateTime.ParseExact() 令人困惑

标签 c# datetime

为什么我可以将该代码应用于其他形式的 .cs

string dt = day + "/" + month + "/" + year;
DateTime newDate = DateTime.ParseExact(dt, "dd/MM/yyyy", null);

总是报错

String was not recognized as a valid DateTime.

必须这样改

"dd/MM/yyyy"  -->   "d/M/yyyy"

但在其他形式的 .cs 中,该代码有效。不需要更改该字符串

最佳答案

通过指定 ddMM,您需要输入 2 个字符宽。您的代码适用于 10/10/2015,但不适用于 1/1/2015

更改您的代码以允许单个日期和月份字符,您会没事的:

DateTime newDate = DateTime.ParseExact(dt, "d/M/yyyy", null);

关于c# - DateTime.ParseExact() 令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902600/

相关文章:

c# - ASP.NET MVC : Align checkbox and label on same line

c# - 无法显示链接字段值表+ReportViewer

python - 日差,Python 3.6

php - 哪个更适合在 MySQL 中存储非公历日期时间? datetime+PHP 将 OR varchar 或 Unix 时间戳转换为 int

c# - DateTime 解析 WinRT Windows 8 RTM 中的错误?

javascript - 使用一致的时区解释解析 javascript 日期?

c# - 在.NET ASPX应用程序中使用ExecuteURL的自定义错误页面不起作用(重定向工作正常)

从嵌套类到包含类的 C# 成员访问

r - 使用 R 构建特定的时间序列图

c# - FluentNhibernate + 私有(private)集