Ashutosh Ashutosh - 2 months ago 18
C# Question

Convert DateTime to string format("yyyyMMdd")

I am having a problem converting a datetime which is in string format but I am not able to convert it to yyyyMMdd format.

my code is:

string tpoc = refSubClaim.BenefitsFolder.BenefitFolderIdNumber.ToString();
string[] tpocinfo = Regex.Split(tpoc,";");

for (int i = 0; i < tpocinfo.Length; i++)
{
switch (i)
{
case 0:
{
string[] tpoc2 = Regex.Split(tpocinfo[0], ",");
claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString();
claimantAuxillaryRecord.TPOCAmount2 = Convert.ToDecimal(tpoc2[1]);
claimantAuxillaryRecord.FundingDelayedBeyondTPOCStartDate2 = tpoc2[2].ToString();
}
break;

Answer

if you have a date in a string with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:

DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy", 
                                  CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");