150

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;
Matt
  • 25,467
  • 18
  • 120
  • 187
Ashutosh
  • 5,614
  • 13
  • 52
  • 84

14 Answers14

239

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");
Falle1234
  • 5,013
  • 1
  • 22
  • 29
  • 4
    Got stuck with your code, this one worked well DateTime.TryParse(stringValue, out outputInDateTime); – DJ' Sep 15 '14 at 12:17
67

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);
Dariusz Woźniak
  • 9,640
  • 6
  • 60
  • 73
  • 7
    This is an old topic, but for those searching, the link above, "culture-specific format" is now a dead link. Here is one that is current and informative [Custom Date and Time Format Strings](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx) –  Oct 11 '12 at 16:03
42

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");
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
11

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

TxtCalStDate.Text = Convert.ToDateTime(objItem["StartDate"]).ToString("yyyy/MM/dd");   
kleopatra
  • 51,061
  • 28
  • 99
  • 211
NSiva
  • 111
  • 1
  • 2
11

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");
MJ Vakili
  • 2,798
  • 1
  • 19
  • 25
Anish
  • 588
  • 6
  • 21
6

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);
Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133
5

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

peter
  • 553
  • 1
  • 5
  • 13
5

Simply just do in this way.

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

Happy coding :)

4

It's the Simple way to convert to format

 DateTime.Now.ToString("yyyyMMdd");
Chiragkumar Thakar
  • 3,616
  • 5
  • 37
  • 49
3

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

SergioMSCosta
  • 324
  • 2
  • 8
2

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.

Matt
  • 74,352
  • 26
  • 153
  • 180
Peter
  • 797
  • 11
  • 35
  • no its a string with yyyy/mm/dd and i need it in yyyyMMdd format – Ashutosh Aug 13 '10 at 15:15
  • and while doing claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString("yyyyMMdd"); it gives some build errors. The best overloaded method match for 'string.ToString(System.IFormatProvider)' has some invalid arguements – Ashutosh Aug 13 '10 at 15:17
  • @Matt - really? You edited a 4+ year response that wasn't even marked as the answer to add a tab? That's a serious bad case of OCD you've got there. – Peter Nov 18 '15 at 08:35
2

From C# 6:

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

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

ben alfasi
  • 21
  • 3
0

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"));
Matt
  • 74,352
  • 26
  • 153
  • 180
  • How about I have a value for `DateTime`? Like `DateTime newDate = DateTime.Parse(Session["date"].ToString());`? – WTFZane Mar 14 '17 at 00:24
0

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"); 
A. Zalonis
  • 1,599
  • 6
  • 26
  • 41
  • 1
    For the love of god (our lord savior Harambe), never use Convert.ToDateTime... This thing is so slow (~100ms)! Just use ParseExact or TryParse - waaaaay faster!!! – Koshera Nov 04 '16 at 22:00