4

I have a date that is stored as a string in the format YYYYDDMM. I would like to display that value in a 'MM/DD/YYYY' format. I am programming in c#. The current code that I am using is as follows:

txtOC31.Text = dr["OC31"].ToString().Trim();
strOC31date = dr["OC31DATE"].ToString().Trim();
DateTime date31 = DateTime.Parse(strOC31date);
strOC31date = String.Format("{0:MM/dd/yyyy}", date31);

However, I am getting an error because the YYYYMMDD string (strOC31date) is not being recognized as a valid datetime.

4

4 回答 4

20

DateTime.ParseExact with an example

string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));
于 2012-08-07T14:31:06.510 回答
11

Use ParseExact() (MSDN) when the string you are trying to parse is not in one of the standard formats. This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).

DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);

Passing null for the format provider will default to DateTimeFormatInfo.CurrentInfo and is safe, but you probably want the invariant culture instead:

DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);

Then your code will work.

于 2012-08-07T14:28:06.370 回答
3

Instead of DateTime.Parse(strOC31date); use DateTime.ParseExact() method, which takes format as one of the parameters.

于 2012-08-07T14:27:44.860 回答
3

You want the method DateTime.ParseExact.

DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);
于 2012-08-07T14:28:23.577 回答