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 tha
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.
You want the method DateTime.ParseExact.
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);
DateTime.ParseExact with an example
string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));
Instead of DateTime.Parse(strOC31date);
use DateTime.ParseExact()
method, which takes format as one of the parameters.