简体   繁体   中英

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?

First of all, DateTime s 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

You can use this for String date

DateTime.ParseExact(dateString, format, provider);

and for provider value

CultureInfo provider = CultureInfo.InvariantCulture;

as mentioned in Microsoft documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM