I have a database script that returns date time string and my problem is that I don’t know what format my string will be. The reason is that I have desktop in different culture and they could return any kind of format. My ultimate goal is, from the string to return the DateTime.
As I am trying to write something I am realizing that I would need to try any kind of format to make sure something comes back to me without an exception.
There should be a better way to do this without trial and error.
This is what I have but it only works for a few formats:
public static DateTime FromQueryResultString(string dttmString)
{
string[] formats = { "dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "yyyyMMdd HH:mm:ss", "dd.MM.yy hh:mm", "M/d/yy h:mm tt", "ddd MMM dd H:mm:ss yyyy", "dd.MM.yy hh:mm", "dd.MM.yy HH:mm","ddd MMM yy H:mm:ss yyyy" };
string name = Thread.CurrentThread.CurrentCulture.Name;
IFormatProvider format = new CultureInfo(name, false);
DateTime formattedDate = DateTime.ParseExact(dttmString, formats, format, DateTimeStyles.None);
}
I think you’re missing a fundamental concept.
Considering that you’re talking about a DataBase script, it’ a script, I immagine, which returns a data from database. Your database has to always hold a DateTime, floating point numbers and other culture sencitive data in one common format. In this case, you will have one single stable Data Access Layer which will recover and manipulates data recovered from Rome, Paris, Beijing or Abu Dhabi. The client program that data will visualize in culture dependent way.
In short: choose one format and store it in that way.
It’s clear that this architecture is not always possible to have, but from my expirience it is possible in 99% of cases.
Hope this helps.