how to tell convert.todatetime that the input is in format dd-mm-yyyy
have written 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.
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_c开发者_如何学JAVAalc = new DateTime();
dt_calc = Convert.ToDateTime(inputt);
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));
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
Have a look at this Code Project that extends the DateTime parsing capabilities. Alternatively there's a Natural Date Parser class on GitHub.
精彩评论