vrijdag 7 januari 2011

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:

dt.ToString("yyyy-MM-dd HH:mm:ss.ss");


for an overview of all possible DateTime formats, I'll refer to http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

Geen opmerkingen:

Een reactie posten