AlexW
AlexW

Reputation: 2589

Date not in correct format

I have a function that checks for null values then converts dates if they are not null the below function just had "08/09/13" sent to it (English format) and i got "String was not recognized as a valid DateTime."

anyone help me as to why? do i need to tell the something somewhere is uses English format?

Thanks

public static DateTime DateTimeCheck(object objDateTime)
        {
            if (objDateTime == null || objDateTime == "")
                return default(DateTime);
            return Convert.ToDateTime(objDateTime);

        }

Upvotes: 0

Views: 213

Answers (5)

stefano m
stefano m

Reputation: 4224

Try this:

DateTime.ParseExact((string)objDateTime,"dd/MM/yyyy",CultureInfo.InvariantCulture);

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98750

I don't understand why you passed an object as a parameter instead of string first of all.

Try this instead;

public static DateTime DateTimeCheck(object objDateTime)
{
   ...
   return DateTime.ParseExact(objDateTime.ToString(),"dd/MM/yy",CultureInfo.InvariantCulture);    
}

Of course, this throws exception if your object is not formatted same as with "dd/MM/yy".

Take a look at;

Upvotes: 1

Lloyd
Lloyd

Reputation: 29668

You might be in a different culture with a different default date format. However you can use ParseExact to parse in the expected format. For example:

 CultureInfo provider = CultureInfo.InvariantCulture;
 DateTime result = DateTime.ParseExact("25/12/82","dd/MM/yy",provider);

Upvotes: 1

thealghabban
thealghabban

Reputation: 448

I know this not what you are looking for but that's how to be sure that some object has date time value in it something like that :

    public static DateTime DateTimeCheck(object objDateTime)
    {
        DateTime dateTime ;
        if (objDateTime != null)
        {
            if (DateTime.TryParse(objDateTime.ToString(), out dateTime))
            {
                return Convert.ToDateTime(objDateTime);
            }
        }

        return default(DateTime);
    }

Upvotes: 0

Alberto
Alberto

Reputation: 15941

You can use the overloaded method that accepts the culture information:

Convert.ToDateTime(o, new CultureInfo("en-Gb"));

To get or set the current culture you can use:

System.Threading.Thread.CurrentThread.CurrentCulture

Upvotes: 1

Related Questions