Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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);
like image 274
user287745 Avatar asked Aug 21 '10 08:08

user287745


People also ask

What is the format of convert ToDateTime?

ToDateTime(value); Console. WriteLine("'{0}' converts to {1} {2} time.", value, convertedDate, convertedDate.

How do I change the date format from yyyy mm dd in C#?

string date = DateTime. ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo. InvariantCulture). ToString("yyyy-MM-dd");

How do I fix string is not recognized as a valid DateTime?

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.


2 Answers

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));
like image 184
Jason Quinn Avatar answered Sep 20 '22 02:09

Jason Quinn


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
like image 35
Oded Avatar answered Sep 19 '22 02:09

Oded