Converting custom Strings to DateTime

One of projects I’m currently working on involves reading a file produced by other tool, that has rather unusual way of storing a date and time. For example 1st of July 2007, 14:00:00 would be stored as 20070701T140000Z (colors added for emphasis).

Using Convert.ToDateTime(string) or DateTime.Parse(string) throws FormatException. Parsing manually (splitting string and parsing its substring to ints to create DateTime object from them) is not very elegant solution. There is however static method DateTime.ParseExact(string, string, IFormatProvider). First parameter is encoded DateTime, second is pattern, and third can be null. How to create pattern you can learn from this msdn article.

Putting it all together, here’s how I parsed those strings to DateTime and DateTime to strings:

DateTime dt = DateTime.ParseExact("20070622T142203Z", "yyyyMMdd'T'HHmmss'Z'", null);

string s = dt.ToString("yyyyMMdd'T'HHmmss'Z'");