如何以不同的格式格式化 DateTime? [英] How do I format a DateTime in a different format?
问题描述
我有一个字符串表示某种格式的日期,我希望采用不同的格式.有人告诉我使用 DateTime.(Try)ParseExact
,所以我做到了:
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);
你看,我想将日期格式化为 dd/MM/yyyy
,所以 26/02/2016
.但是,此代码会引发 FormatException:
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.
如何以不同的方式格式化 DateTime?
How can I format a DateTime differently?
推荐答案
首先,DateTimes 没有格式.DateTime 占据一席之地及时和 标志 指示该时刻是否本地、Utc 或 未指定.
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.
唯一的时刻 DateTime 被格式化,即当您将其值作为字符串输出时.
The only moment a DateTime gets formatted, is when you output its value as a string.
您提供给 (Try)ParseExact
的格式字符串是要解析的日期(时间)字符串的格式.请参阅 MSDN:自定义日期和时间格式字符串 了解如何编写自己的格式字符串.
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);
现在 parsedDate
拥有一个 DateTime 值,您可以以所需的格式输出(请注意,您必须对 /
进行转义,因为它将被解释为日期当前文化的分隔符",如上述 MSDN 链接):
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
这篇关于如何以不同的格式格式化 DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!