Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert YYYYMMDD string to MM/DD/YYYY string

Tags:

c#

datetime

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.

like image 486
JTRookie86 Avatar asked Nov 28 '22 01:11

JTRookie86


2 Answers

DateTime.ParseExact with an example

string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));
like image 162
Steve Avatar answered Dec 21 '22 23:12

Steve


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.

like image 39
James Michael Hare Avatar answered Dec 22 '22 00:12

James Michael Hare