I have a string like below :
"9/30/2017 12:00:00 AM"
Would love to convert it to format yyMMdd
var evan = dataRow["ValueDate"].ToString(); //Output is "9/30/2017 12:00:00 AM"
DateTime dt = DateTime.ParseExact(evan,"yyMMdd",CultureInfo.InvariantCulture);
Than to diplay :
dt.ToString("yyMMdd");
Error Message : String was not recognized as a valid DateTime for format yyMMdd
What is my mistake?
Thank you
ParseExact
is for parsing a string that's being input in a specific format. To display the string, you pass the format string to the ToString
method:
var evan = dataRow["ValueDate"].ToString("yyMMdd");
DateTime.ParseExact
is expecting the data you give it to be in the EXACT format you specify. Your string 9/30/2017 12:00:00 AM
does not match your format yyMMdd
. So either try using just DateTime.Parse
, or make your format match the data. Something like
DateTime dt = DateTime.ParseExact(evan,"M/dd/yyyy HH:mm:ss tt",CultureInfo.InvariantCulture);`
Then you should be able to do dt.ToString("yyMMdd");
After gathering intel from posters I succed in understanding and solving my mistake :
After carefully consulting MSDN this is the solution I was looking for :
Input :
dataRow["ValueDate"].ToString() // "9/30/2017 12:00:00 AM"
Code :
DateTime convertedDate;
convertedDate=Convert.ToDateTime(dataRow["ValueDate"].ToString());
var evan = convertedDate.ToString("yyMMdd");
Output :
"170930" //just like I need
Like Michael sharp explained earlier :
DateTime.ParseExact
is expecting the data you give it to be in the EXACT format you specify. My string 9/30/2017 12:00:00 AM
did not match my format yyMMdd
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.