0

I have the following data in my date field of my GridView: 2016-01-24T00:00:00 Before updating that field, I want to store that value in "dd/MM/yyyy" format.

To do that I'm doing the following:

IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
string formattedHolDate = DateTime.ParseExact(holDate, "dd/MM/yyyy", culture).ToString("MM/dd/yyyy");

However, when running the code, I have the following error:

String was not recognized as a valid DateTime.

What is the right way to handle it?

gene
  • 2,098
  • 7
  • 40
  • 98
  • 1
    why are you telling c# to expect `dd/mm/yyyy` formatted string, then pass in `yyyy-mm-ddThh:mm:ss`? and then why are you expecting C# to read your mind and figure out what you REALLY wanted? – Marc B Feb 22 '16 at 20:47
  • I know it was not right way to do it, but format should I use in that case? – gene Feb 22 '16 at 20:49
  • tell c# what format your input string **IS**. formatting for output comes AFTER you've successfully parsed that input. – Marc B Feb 22 '16 at 20:51

1 Answers1

0

How I am reading your question.

2016-01-24T00:00:00 (what you have)

"dd/MM/yyyy" (what you want)

IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
var myDate = DateTime.Parse(holDate);
string myFormattedDateString = myDate.ToString("dd/MM/yyyy");

You had some stuff turned around.

  • Parse = converting from string to a date (or other object depending on the implementation)
  • ToString - converting from object to a string representation

Edit

As 2016-01-24T00:00:00 is actually an ISO 8601 representation of a DateTime you do not need ParseExact, just Parse will do.

Community
  • 1
  • 1
Igor
  • 60,821
  • 10
  • 100
  • 175