Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

c# - 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...