Convert date time to string and back to date time

早过忘川 提交于 2019-12-13 02:44:24

问题


I'm having a troubles with converting strings to DateTime. Here is what I have. First I convert current date to string (this will be folder name).

string dateString = string.Format("{0:yyyy-MM-dd_HH-mm-ss}", DateTime.Now);

Output like this

2013-05-16_09-32-47

Then I create a folder. During program execution I get this folder and I need to convert it's name back to DateTime. Try to make it like this

DateTime directoreDate = DateTime.ParseExact(directory.Name, "0:yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);

But it throws FormatException. Can anybody tell me why this happening.


回答1:


You are using the same composite format string that you used to format the original DateTime. This is not needed for ParseExact - drop the 0: from it:

DateTime directoreDate = DateTime.ParseExact(directory.Name, 
                                             "yyyy-MM-dd_HH-mm-ss", 
                                             CultureInfo.InvariantCulture);



回答2:


Use

DateTime directoreDate = DateTime.ParseExact(directory.Name, "yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);



回答3:


Remove 0: from DateTime.ParseExact, It was used as a place holder in string.Format(). Use as :

DateTime directoreDate = DateTime.ParseExact(directory.Name,
                                          "yyyy-MM-dd_HH-mm-ss", 
                                           CultureInfo.InvariantCulture);


来源:https://stackoverflow.com/questions/16580673/convert-date-time-to-string-and-back-to-date-time

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