NoughT NoughT - 1 year ago 43
C# Question

Conflict in system time format and database return time string value format in C#

I was using

to convert my date string value to Date object.

Here is the code that I use to convert my date string to

DateTime.ParseExact(“ my date string value from database ”, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture) ;

My database returns a string value like this
“25/9/2016 00:00:00”
But when I was debug my code it continuously gave me that string is not valid string to convert to

Finality I have to change my laptop date time format to “d/M/yyyy H:mm:ss” to make my database string value to valid string value.

So how can I guarantee that my code work in server. What is the solution for this kind of situations ?? Do I have to check server date time format and change to format string according to it before build my code.??

Answer Source

ParseExact with the format "dd/MM/yyyy HH:mm:ss" will fail when you give it the string “25/9/2016 00:00:00” because the month is just a single digit.

Changing the format to "dd/M/yyyy HH:mm:ss" is the correct solution.

However, you shouldn't be storing dates & times in your database as strings as you will keep encountering this sort of problem.

If you really have to have strings then you can use the overload of ParseExact that takes an array of allowable formats so you can cope with multiple formats as in the example from that page:

  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[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                          "5/1/2009 6:32:00", "05/01/2009 06:32", 
                          "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00",
                          "08/28/2015 16:17:39.125", "08/28/2015 16:17:39.125000" };
  DateTime dateValue;

  foreach (string dateString in dateStrings)
     try {
        dateValue = DateTime.ParseExact(dateString, formats, 
                                        new CultureInfo("en-US"), 
        Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
     catch (FormatException) {
        Console.WriteLine("Unable to convert '{0}' to a date.", dateString);