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 1:

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

Solution 2:

Parsing DateTime:

To parse a DateTime, use one of the following methods:

  • DateTime.Parse
  • DateTime.ParseExact

Alternatively, you may use try-parse pattern:

  • DateTime.TryParse
  • DateTime.TryParseExact

Read more about Custom Date and Time Format Strings.

Converting DateTime to a string:

To return a DateTime as a string in "yyyyMMdd" format, you may use ToString method.

  • Code snippet example: string date = DateTime.ToString("yyyyMMdd");
  • Note upper-cased M's refer to months and lower-cased m's to minutes.

Your case:

In your case, assuming you don't want to handle scenario when date is different format or misssing, it would be most convenient to use ParseExact:

string dateToParse = "20170506";
DateTime parsedDate = DateTime.ParseExact(dateToParse, 
                                          "yyyyMMdd",
                                          CultureInfo.InvariantCulture);

Solution 3:

You can convert your string to a DateTime value like this:

DateTime date = DateTime.Parse(something);

You can convert a DateTime value to a formatted string like this:

date.ToString("yyyyMMdd");