user287745
user287745

Reputation: 3171

how to tell convert.todatetime that the input is in format dd-mm-yyyy

have written code that is supposed to

My code works fine when the user gives input in the default format but when the user enters a date like dd-mm-yyyy instead of mm/dd/yyyy(default), it doesn't work.

How can I change the convert function to take care of this?

    DateTime dt_calc = new DateTime();
    dt_calc = Convert.ToDateTime(inputt);

Upvotes: 5

Views: 7449

Answers (3)

Jason Quinn
Jason Quinn

Reputation: 2563

To convert a date in the format dd-mm-yyyy use:

var dateValue = DateTime.Parse("11/03/1989", new CultureInfo("en-GB", false));

But don't forget to add the System.Globalization in the header or just do it inline:

var dateValue = DateTime.Parse("11/03/1989", new System.Globalization.CultureInfo("en-AU", false));

Upvotes: 7

Oded
Oded

Reputation: 499042

Don't use Convert - DateTime has Parse, TryParse, ParseExact and TryParseExact methods that take a IFormatProvider though for this simply using parse should work:

DateTime dt_calc = DateTime.Parse(inputt);

If you would rather be safe, use `TryParse:

DateTime dt_calc;
DateTime.TryParse(inputt, out dt_calc); // TryParse returns true if success, false if not

Upvotes: 2

Lazarus
Lazarus

Reputation: 43084

Have a look at this Code Project that extends the DateTime parsing capabilities. Alternatively there's a Natural Date Parser class on GitHub.

Upvotes: 1

Related Questions