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_calc = new DateTime();
dt_calc = Convert.ToDateTime(inputt);
ToDateTime(value); Console. WriteLine("'{0}' converts to {1} {2} time.", value, convertedDate, convertedDate.
string date = DateTime. ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo. InvariantCulture). ToString("yyyy-MM-dd");
By parsing the string representation of a date and time value. The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. The following example uses the Parse method to parse a string and convert it to a DateTimevalue.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With