views:

44

answers:

3

have written a code, that is supposed to

  • take time and date input from the user

  • and convert it to datetime format

  • add some value to hrs and display it.

works fine, when user gives input in the default format.

but what is user enters like dd-mm-yyyy instead of mm/dd/yyyy(default)

how to tel the convert function to take care of this?

    DateTime dt_calc = new DateTime();
    dt_calc = Convert.ToDateTime(inputt);
+1  A: 

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
Oded
I guess you can try a number of known formats, and see which result in a valid entry. Only the 'ParseExact' methods take a format string however.
Lazarus
+1  A: 

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

Lazarus
+3  A: 

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

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