如何使用不同的格式格式化DateTime? [英] How do I format a DateTime in a different format?
问题描述
我有一个字符串表示某种格式的日期,我希望格式不同。有人告诉我要使用 DateTime(尝试)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:
字符串未被识别为有效的DateTime。
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 unknown, and that's it.
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屋!