aynakolik
aynakolik

Reputation: 99

String was not recognized as a valid DateTime Issue

I have a method,

public static DateTime ToDate(this object value)
{
    return DateTime.ParseExact(value.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture);
}

When i run this code with this code,

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(DateTime.Now.ToDate().ToString());
}

And there is a error on program like this,

String was not recognized as a valid DateTime

How can i solve this problem? Thanks.

Upvotes: 2

Views: 343

Answers (3)

Lamloumi Afif
Lamloumi Afif

Reputation: 9081

I suggest to use the TryParseExact

Then you choose the date format that you need

For example :

public static DateTime ToDate(this object value)
{
    DateTime OutputDate ;
    DateTime.TryParseExact(value, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out OutputDate);
    return OutputDate ?? DateTime.Now  ;
}

In the example : the format is "dd.MM.yyyy" and the input date string is value. The OutputDate will take as value the new datetime object and if the instruction fails it will take null.

Please, verify the format of the date and replace it in the example above if you need

Upvotes: 0

sakura-bloom
sakura-bloom

Reputation: 4594

The problem you're having is that your extension method tries to parse the string specifically in the dd.MM.yyyy format. And you're testing your extension method using the DateTime.Now which returns a DateTime in a format of a current culture on your machine (including hours, minutes, etc.), which may may not be in a dd.MM.yyyy format. You can test your extension method as follows: DateTime.Now.ToString("dd.MM.yyyy").ToDate()

However, If I understand correctly what you're trying to do it is better to change the extension method as follows.

public static DateTime ToDate(this string value, string format)
{
    return DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
}

and use it as follows

private void button1_Click(object sender, EventArgs e)
{
    // Testing the extension method.
    MessageBox.Show(DateTime.Now.ToString("dd.MM.yyyy").ToDate("dd.MM.yyyy").ToString());
}

Or, if you specifically receive a DateTime in dd.MM.yyyy because of the localization it is better to set the culture of your application globally like so.

// Substitute appropriate culture.
Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU");
Thread.CurrentThread.CurrentCulture  = new CultureInfo("ru-RU");

That way you will not need your extension method since the DateTime will always be in the correct format.

Upvotes: 1

karim
karim

Reputation: 167

your first function must be as follow :

public static DateTime ToDate(this object value)
{
     string date = value.ToString("dd.MM.yyyy");
     DateTime dt = Convert.ToDateTime(date); 
     return dt;
}

Upvotes: 0

Related Questions