DateTime Conversion and Parsing DateTime.Now.ToString(“MM/dd/yyyy hh:mm:ss.fff”)

余生长醉 提交于 2019-11-28 08:47:32

问题


I store some DateTime in a CSV log with:

DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")

When I try to read it I found something like:

"05/15/2012 10:09:28.650"

The problem is when I try to cast it as a DateTime again...

DateTime.Parse("05/15/2012 10:09:28.650");

Throws an Exception "Invalid DateTime" or something like that...

How can I properly re-read the DateTime?


回答1:


You can use DateTime.ParseExact:

string format = "MM/dd/yyyy hh:mm:ss.fff";
DateTime d = DateTime.ParseExact("05/15/2012 10:09:28.650",
                                format,
                                System.Globalization.CultureInfo.InvariantCulture);

Standard Date and Time Format Strings




回答2:


use DateTime.ParseExact with specifying the format

String dateStr=DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff");
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss.fff",System.Globalization.CultureInfo.InvariantCulture);



回答3:


You should use this method to parse your string. You would have to make a class, imlementing IFormatProvider, but if you want to use a custom DateTime format, it's the best method I can think of.



来源:https://stackoverflow.com/questions/10599209/datetime-conversion-and-parsing-datetime-now-tostringmm-dd-yyyy-hhmmss-fff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!