Brian Newtz wrote:
> 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.
--
mikeb
|