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

wrote code that should

  • take time and date from user

  • and convert it to datetime format

  • add some value to hrs and display it.

My code works fine when the user enters input in the default format, but when the user enters a date such as dd-mm-yyyy instead of mm / dd / yyyy (by default), it does not work.

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

    DateTime dt_calc = new DateTime();
    dt_calc = Convert.ToDateTime(inputt);
+5
source share
3 answers

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

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

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

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

Convert - DateTime Parse, TryParse, ParseExact TryParseExact, IFormatProvider, :

DateTime dt_calc = DateTime.Parse(inputt);

, "TryParse:

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

Take a look at this Code Project , which extends DateTime parsing. GitHub also has a Natural Date Parser class .

+1
source

All Articles