If there is a thing that we all fear and hate is Date/Time conversions. The different formats used around the world are a real nightmare for data standarization and if there is a thing that really drives me mad are the different separators that can be used. The typical range of separators is ‘/’, ‘-‘, ‘.’, ‘_’. For me more than one is too many already! 🙂
Just recently I had to face another date/time conversion and looking around for an elegant solution I found this:
CultureInfo SAPDOB = new CultureInfo(“en-gb”, false);
SAPDOB.DateTimeFormat.DateSeparator = “.”;
SAPDOB.DateTimeFormat.FullDateTimePattern = “ddMMyyyy”;
There is an object type called CultureInfo, which we can set to a Windows culture, in this case “en-gb”. That means that the date/time that this new object, which I called SAPDOB (for SAP Date of Birth) will hold will follow the en-gb standard. What it makes this peace of code very interesting is that we can alter the format of the internal date/time in SAPDOB and adapt it to map the string format that it’s comming from our datasource (in my case a SAP table).
The dates that I’m retrieving from SAP have the dd.mm.yyyy format. In this case the separator is a ‘.’. CultureInfo objects allow you to specify which date separator you will use, in my case I configured it to use ‘.’. You can also specify which DateTime pattern your data will follow, in my case was “ddMMyyyy”.
Once configured the CultureInfo object we can use it to convert the date/time strings coming from SAP to DateTime objects. The Convert.ToDateTime function accepts a CultureInfo object as parser to understand the string in the first parameter and it will return you back a DateTime object, which later you could use as a fully working standard DateTime object. Yuhuuu!!!
I hope this little piece of code makes you as happy as it made me 🙂