l3utterfly l3utterfly - 1 year ago 434
C# Question

TryParse DateTime c# dd/mm/yyyy hh:ss

I know this has been asked a lot of times, but none seems to relate to my problem (all answers specifies another datetime format than the one which is giving me issues):

Convert string(dd/MM/yyyy hh:mm) to datetime format

Converting a String to DateTime

Convert dd/MM/yyyy hh:mm:ss.fff from String to DateTime in C#

Specific example:

Input is a string:

24/10/2016 10:20

I call
DateTime.TryParse(input, out output)

The output is a
{1/1/0001 12:00:00 AM}

Why? This is a perfectly valid input format from what I know...

Things I tried / restrictions:

  • Change the input to have a second:
    24/10/2016 10:20:00
    , it works

  • Use
    , specifying this format, it works

However, I cannot use both these solutions as the input is user defined, I cannot force the user to stick to a specific input, and want to accept any reasonably formatted date times. The format I specified in the question seems reasonable (it's the default format outputted by Excel).

I can assume the culture is

Any help would be appreciated.

The top answer to the first question throws an exception... I don't know why that's even up-voted.

Update 2:

Since there are a lot of close requests, here's some minimal working code (duplicated from the answer by Mohit Shrivastava):

string dtstr = "24/10/2016 10:20";
DateTime outdt;
DateTime.TryParse(dtstr, out outdt);

Minimal code

Answer Source

Your output is 1/1/0001 12:00:00 AM which is the min value of the DateeTime object, which means that the conversion failed(as per this documentation). The string input is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture. So the problem is the format of the date-string that you are passing.

Try using TryParseExtract in a smarter way since you know the format of the string input, like the following:

  string dateString ="24/10/2016 10:20";
  string formatString="dd/MM/yyyy HH:mm";
  DateTime dateValue;
  CultureInfo enUS = new CultureInfo("en-US"); // is up to you
  if (DateTime.TryParseExact(dateString, formatString , enUS, 
                                 DateTimeStyles.None, out dateValue))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download