Reputation: 131
Problem
I am trying to convert String
in DateTime
format and again converted DateTime
to String
Case # 1
string time = "20120718 00:56:03";
DateTime theTime =DateTime.ParseExact(time,"MM-dd-yyyy HH:mm:ss",CultureInfo.InvariantCulture,DateTimeStyles.None);
string convertedTime = theTime.ToString("MM-dd-yyyy HH:mm:ss");
Case # 2
string time = "20120718 00:56:03";
string CallDate_DBFormat = Convert.ToDateTime(time).ToString("MM-dd-yyyy HH:mm:ss");
DateTime CallTime = Convert.ToDateTime(CallDate_DBFormat);
string convertedTime = CallTime.ToString("MM-dd-yyyy HH:mm:ss");
In both cases I get the Exception that
String was not recognized as a valid DateTime
Upvotes: 0
Views: 4340
Reputation: 98740
From documentation of DateTime.ParseExact
method;
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
In your case #1, they are not. Use yyyyMMdd HH:mm:ss
format instead.
string time = "20120718 00:56:03";
DateTime theTime = DateTime.ParseExact(time,"yyyyMMdd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
string convertedTime = theTime.ToString("MM-dd-yyyy HH:mm:ss");
For case #2, we need to know your CurrentCulture
property. Why?
Because this method uses DateTime.Parse
method with CurrentCulture
. Here how it's implemented;
public static DateTime ToDateTime(String value)
{
if (value == null)
return new DateTime(0);
return DateTime.Parse(value, CultureInfo.CurrentCulture);
}
Probably yyyyMMdd HH:mm:ss
format is not a standard date and time format for your CurrentCulture
and that's why this method throws FormatException
.
Upvotes: 3
Reputation: 5264
Use this:
string time = "20120718 00:56:03";
DateTime theTime = DateTime.ParseExact(time, "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None);
string convertedTime = theTime.ToString("yyyy-dd-MM HH:mm:ss");
Upvotes: 0
Reputation: 4963
Do like this. You have set invalid format to parse the string into DateTime
Look at your DateTime
string format.
string time = "20120718 00:56:03";
DateTime theTime =DateTime.ParseExact(time,"yyyyMMdd HH:mm:ss",CultureInfo.InvariantCulture,DateTimeStyles.None);
string convertedTime = theTime.ToString("MM-dd-yyyy HH:mm:ss");
Upvotes: 1