简体   繁体   中英

System.Format exception in C#

objDR["sidate"].ToString() has the date in this format "01-17-78" where objDR is a datarow. When i am doing the following :

    Convert.ToDateTime(objDR["sidate"].ToString())

I am getting a System.Format exception. What could possibly be causing this?

Edit: The exception is not coming now.Refer Marked answer. Just one more question : the "MM-dd-yy" used in the middle is used for conversion of date from one format to other or it is used for some other purpose? Because i changed it to "Md-yy" but the format did not change.

You have to provide dateformat.
Try this
DateTime dt = DateTime.ParseExact("01-17-78", "MM-dd-yy", CultureInfo.InvariantCulture);

The Convert.ToDateTime() method takes in consideration your current culture in order to use that method you must make sure that the format of the DateTime you are passing to the method is the same format as your current culture.

Otherwise, you can do the following:

var date = DateTime.Parse(objDR["sidate"].ToString(),CultureInfo.InvariantCulture);

Another solution is to use the DateTime.ParseExact() method:

DateTime dt = DateTime.ParseExact(objDR["sidate"].ToString(), "MM-dd-yy", CultureInfo.InvariantCulture);

Link to DateTime struct in MSDN.
Link to DateTime.Parse(String, IFormatProvider) method overload in MSDN.
Link to the Convert.ToDateTime() method in MSDN.
Link to the DateTime.ParseExact() method on MSDN.

The problem is your current culture. Convert.ToDateTime uses the current culture to determine the convert format see the remakrs.

But one solution is to use

DateTime.Parse(objDR["sidate"].ToString(), CultureInfo.InvariantCulture)
so the culture is programmer given.

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