Initializing a DateTime variable with a string date

G

Gary Rynearson

I am looking to turn the string "20051211 14:22:33" into a dateTime variable
whose date is December 11, 2005 and time is 2:22:33 PM. I have tried
several approaches, I MUST be missing something simple. I have spent more
time on this than anyone should have to.

DateTime myDateTime = DateTime.Parse ("20051211 14:22:33")

I get a "Syste;m.FormatExcption: String was not recognized as a valid
DateTime" error.
 
M

Mattias Sjögren

Gary,

You can call DateTime.ParseExact and pass in a format string
describing what the date is formatted like.


Mattias
 
G

Gary Rynearson

Mattias

I have tried this, but cannot come up with the correct string. This is
exactly the fustrating detail I am looking for help with.

Gary
 
G

Goran Sliskovic

Gary Rynearson said:
Mattias

I have tried this, but cannot come up with the correct string. This is
exactly the fustrating detail I am looking for help with.

Gary
....
try:
DateTime myDateTime = DateTime.ParseExact("20051211 14:22:33", "yyyyMMdd
HH:mm:ss", DateTimeFormatInfo.InvariantInfo);

Regards,
Goran
 
G

Gary Rynearson

Goran

Thanks very much for you help. Your suggestion works exactly as I hoped.
Note: the DateTimeFormatInfo.InvariantInfo class / property requires "using
System.Globalization;"

Gary
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top