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

C#StringDatetime

C# Problem Overview


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;

C# Solutions


Solution 1 - C#

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 - C#

Parsing DateTime:

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

Alternatively, you may use try-parse pattern:

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 - C#

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

Solution 4 - C#

String to yyyy-MM-dd date format: Example:

TxtCalStDate.Text = Convert.ToDateTime(objItem["StartDate"]).ToString("yyyy/MM/dd");   

Solution 5 - C#

If you want to have DATE as string with TIME as well. We can do like this:

    //Date and Time is taking as current system Date-Time    
    DateTime.Now.ToString("yyyyMMdd-HHmmss");

Solution 6 - C#

Use DateTime.TryParseExact() if you want to match against a specific date format

   string format = "yyyyMMdd"; 
    DateTime dateTime;
    DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
                                             DateTimeStyles.None, out dateTime);

Solution 7 - C#

You could use DateTime.TryParse() instead of DateTime.Parse().
With TryParse() you have a return value if it was successful and with Parse() you have to handle an exception

Solution 8 - C#

Simply just do in this way.

string yourFormat = DateTime.Now.ToString("yyyyMMdd");

Happy coding :)

Solution 9 - C#

> no its a string with yyyy/mm/dd and i need it in yyyyMMdd format

If you only need to remove the slashes from a string don't you just replace them?

Example:

myDateString = "2013/03/28";
myDateString = myDateString.Replace("/", "");

myDateString should now be "20130328".

Less of an overkill :)

Solution 10 - C#

It's the Simple way to convert to format

 DateTime.Now.ToString("yyyyMMdd");

Solution 11 - C#

Based on the property names it looks like you are trying to convert a string to a date by assignment:

claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString();

It is probably due to the current UI culture and therefore it cannot interpret the date string correctly when assigned.

Solution 12 - C#

From C# 6:

var dateTimeUtcAsString = $"{DateTime.UtcNow:o}";

The result will be: "2019-01-15T11:46:33.2752667Z"

Solution 13 - C#

A more simple way I came across while searching for this answer as well;

string date = DateTime.Now.ToString("yyyyMMdd", System.Globalization.CultureInfo.GetCultureInfo("en-US"));

Solution 14 - C#

You can try these codes

claimantAuxillaryRecord.TPOCDate2  = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd"); 

Or

claimantAuxillaryRecord.TPOCDate2 = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd hh:mm:ss"); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshutoshView Question on Stackoverflow
Solution 1 - C#Falle1234View Answer on Stackoverflow
Solution 2 - C#Dariusz WoźniakView Answer on Stackoverflow
Solution 3 - C#SLaksView Answer on Stackoverflow
Solution 4 - C#NSivaView Answer on Stackoverflow
Solution 5 - C#AnishView Answer on Stackoverflow
Solution 6 - C#Mudassir HasanView Answer on Stackoverflow
Solution 7 - C#peterView Answer on Stackoverflow
Solution 8 - C#Prashant-SystematixView Answer on Stackoverflow
Solution 9 - C#SergioMSCostaView Answer on Stackoverflow
Solution 10 - C#manoj kumarView Answer on Stackoverflow
Solution 11 - C#PeterView Answer on Stackoverflow
Solution 12 - C#ben alfasiView Answer on Stackoverflow
Solution 13 - C#Enrique Ortiz SánchezView Answer on Stackoverflow
Solution 14 - C#A. ZalonisView Answer on Stackoverflow