How do I format a DateTime in a different format?

I have a string representing a date in a certain format, that I wish to format differently. Someone told me to use DateTime.(Try)ParseExact, so I did:

var dateString = "2016-02-26";
var formatString = "dd/MM/yyyy";

var parsedDate = DateTime.ParseExact(dateString, formatString, null);

You see, I want to format the date as dd/MM/yyyy, so 26/02/2016. However, this code throws a FormatException:

String was not recognized as a valid DateTime.

How can I format a DateTime differently?


Solution 1:

First of all, DateTimes have no format. A DateTime holds a moment in time and a flag indicating whether that moment is Local, Utc or Unspecified.

The only moment a DateTime gets formatted, is when you output its value as a string.

The format string you provide to (Try)ParseExact is the format that the date(time) string to parse is in. See MSDN: Custom Date and Time Format Strings to learn how you can write your own format string.

So the code you're looking for to parse that string is this, and again, make sure the format string matches the format of the input date string exactly:

var dateString = "2016-02-26";
var formatString = "yyyy-MM-dd";

var parsedDate = DateTime.ParseExact(dateString, formatString, null);

Now parsedDate holds a DateTime value that you can output in your desired format (and note that you'll have to escape the /, as it'll be interpreted as "the date separator character for the current culture", as explained in above MSDN link):

var formattedDate = parsedDate.ToString("dd\\/MM\\/yyyy");

This will format the date in the desired format:

26/02/2016