Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParse issue with dates of yyyy-dd-MM format

I have the following date in string format "2011-29-01 12:00 am" . Now I am trying to convert that to datetime format with the following code:

DateTime.TryParse(dateTime, out dt);  

But I am alwayws getting dt as {1/1/0001 12:00:00 AM} , Can you please tell me why ? and how can I convert that string to date.

EDIT: I just saw everybody mentioned to use format argument. I will mention now that I can't use the format parameter as I have some setting to select the custom dateformat what user wants, and based on that user is able to get the date in textbox in that format automatically via jQuery datepicker.

like image 739
Rocky Singh Avatar asked Jan 17 '11 23:01

Rocky Singh


People also ask

What is DateTime TryParse?

The DateTime TryParse method converts the string representation of a date and time to a DateTime object and returns true if the conversion was successful and false if otherwise.

What is DateTime TryParse in C#?

TryParse(String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

How do I use DateTime TryParse in Uipath?

TryParse Method (System) Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded. @opas1216 - you can use the regular expression to validate the date… you can use below expression to verify/validate the date string.


2 Answers

This should work based on your example "2011-29-01 12:00 am"

DateTime dt; DateTime.TryParseExact(dateTime,                         "yyyy-dd-MM hh:mm tt",                         CultureInfo.InvariantCulture,                         DateTimeStyles.None,                         out dt); 
like image 85
BrokenGlass Avatar answered Oct 10 '22 16:10

BrokenGlass


You need to use the ParseExact method. This takes a string as its second argument that specifies the format the datetime is in, for example:

// Parse date and time with custom specifier. dateString = "2011-29-01 12:00 am"; format = "yyyy-dd-MM h:mm tt"; try {    result = DateTime.ParseExact(dateString, format, provider);    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) {    Console.WriteLine("{0} is not in the correct format.", dateString); } 

If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.

If it's likely that the input will be incorrect (user input for example) it would be better to use TryParseExact rather than use exceptions to handle the error case:

// Parse date and time with custom specifier. dateString = "2011-29-01 12:00 am"; format = "yyyy-dd-MM h:mm tt"; DateTime result; if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result)) {    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } else {    Console.WriteLine("{0} is not in the correct format.", dateString); } 

A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:

// A list of possible American date formats - swap M and d for European formats string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",                     "M/d/yyyy h:mm", "M/d/yyyy h:mm",                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",                    "MM/d/yyyy HH:mm:ss.ffffff" }; string dateString; // The string the date gets read into  try {     dateValue = DateTime.ParseExact(dateString, formats,                                      new CultureInfo("en-US"),                                      DateTimeStyles.None);     Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue); } catch (FormatException) {     Console.WriteLine("Unable to convert '{0}' to a date.", dateString); }                                                

If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.

The main drawback with this approach is that you will still have ambiguous dates. The formats are tried in order so no matter what it'll try the European format before the American (or vice versa) and cover anything where the day is less than 13 to a European formatted date even if the user thought they were entering an American formatted date.

like image 20
ChrisF Avatar answered Oct 10 '22 15:10

ChrisF