简体   繁体   English

将带有日期和时间的短 DateTime 字符串转换为 DateTime

[英]Convert a short DateTime string with date and time to DateTime

Having trouble with my Android project here trying to convert a string of DateTime into an actual DateTime object. here's the code I wrote:我的 Android 项目在这里尝试将 DateTime 字符串转换为实际的 DateTime object 时遇到问题。这是我编写的代码:

string strDateTime = reminder.Date + " " + ((ReminderByTime)reminder).ReminderTime;
userDateTime = DateTime.ParseExact(strDateTime, "MM/dd/yyyy HH/mm", null);

While running the problem I've checked the values and they do coordinate:在运行问题时我检查了值并且它们确实协调:调试窗口的屏幕截图

How can I fix this?我怎样才能解决这个问题?

When you see Exact in the name of the ParseExact() method, it means it!当您在ParseExact()方法的名称中看到Exact时,这就是它的意思! The method is notoriously unforgiving about small typos or format variations.众所周知,该方法对小的拼写错误或格式变化是无情的。

In this case, the time portion of the format string uses a different separator than the actual value.在这种情况下,格式字符串的时间部分使用与实际值不同的分隔符。 HH/mm , which uses a / , does not match 18:20 , which uses a colon ( : ).使用/HH/mm与使用冒号 ( :18:20不匹配。

Therefore your format string needs to look like this:因此,您的格式字符串需要如下所示:

MM/dd/yyyy HH:mm

In the future, I also advise you to avoid posting screen shots of technical information like debugger results.以后,我还建议您避免发布调试器结果等技术信息的屏幕截图。 I know of no faster way to attract downvotes to your questions, and it's really MUCH better for us to see that kind of information as well-formatted text instead.我知道没有更快的方法来吸引对您的问题的反对票,而且我们将这种信息视为格式正确的文本真的更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM