Search code examples
c#stringdatetime

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?


I am having a problem converting a datetime which is in string format but I am not able to convert it using "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;

Solution

  • 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");