How do I format a DateTime in a different format?

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

Leave a Comment