问题
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