简体   繁体   中英

String was not recognized as a valid DateTime When Converting String to DateTime

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

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 .

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");

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");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM