DateTime.Parse - can't figure out how to make this work.

G

Guest

Hi everyone

I was just wondering if I'm going about this in the wrong way, since I can't get things to work correctly. I have an integer that I want to convert to a string, and then a DateTime. The string is in the format of "yyyyMMdd". I have the following

[start code

DateTimeFormatInfo dtfi = new DateTimeFormatInfo()
dtfi.LongDatePattern = "yyyyMMdd"

e.Item.Cells[1].Text = DateTime.Parse(Convert.ToString(r["run_date"]), dtfi).ToShortDateString()

[end code

The code fails on DateTime.Parse with this error

"String was not recognized as a valid DateTime.

I've verified that the Convert.ToString(r["run_date"]) part returns a string like "20040203". I've also tried setting the DateTimeFormatInfo's ShortDatePattern as well and that doesn't work either. What am I doing wrong

Thanks in advance
-Brian
 
G

Guest

i could be wrong, but you need the slashes "/" between the parts of the date. i've had more luck with Convert.ToDateTime() than with DateTime.Parse, though they may actually do the exact same thing.

hth
jayson
 
M

mikeb

Brian said:
Hi everyone!

I was just wondering if I'm going about this in the wrong way, since I can't get things to work correctly. I have an integer that I want to convert to a string, and then a DateTime. The string is in the format of "yyyyMMdd". I have the following:

[start code]

DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
dtfi.LongDatePattern = "yyyyMMdd";

e.Item.Cells[1].Text = DateTime.Parse(Convert.ToString(r["run_date"]), dtfi).ToShortDateString();

[end code]

The code fails on DateTime.Parse with this error:

"String was not recognized as a valid DateTime."

I've verified that the Convert.ToString(r["run_date"]) part returns a string like "20040203". I've also tried setting the DateTimeFormatInfo's ShortDatePattern as well and that doesn't work either. What am I doing wrong?

It seems that DateTime.Parse() does not handle date strings which have
no delimiters between the components of the date. If you change your
LongDatePattern to "yyyy MM dd" and change the actual format of your
date strings to have spaces between the parts, then your code works fine.

To get things to work with your non-delimited date strings, use
DateTime.ParseExact():

DateTime.ParseExact( Convert.ToString(r["run_date"]), "yyyyMMdd",
dtfi);

should work for you.
 

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