Ehbit ninja's blog

Our IT ninja's blog about their professional experiences with IT technologies

Converting DatetTime from and to Custom String format

Converting from String to DateTime

Using Convert.ToDateTime method might give you the error ‘String was not recognized as a valid DateTime’.
Following code for example will result in an error:

DateTime dt = Convert.ToDateTime("20100228");

You can simply do the conversion by defining the dateTime format yourself as follows:

DateTime dt = DateTime.ParseExact("20100228", "yyyyMMdd", new System.Globalization.DateTimeFormatInfo())

Converting from DateTime to String

To convert a DateTime to String is even easier, just use following code:



for an overview of all possible DateTime formats, I’ll refer to