我怎么能转换日期字符串格式,从X要格式化Y' [英] How can I convert a date string from format X to format Y?
问题描述
我有一个包含一些格式X中的日期的字符串(如 12/31/2015
)。我怎样才能将它转换为格式化Y(如 2015年12月31日00:00:00
)?
I have a string containing a date in some format X (e.g. 12/31/2015
). How can I convert it to format Y (e.g. 2015-12-31 00:00:00
)?
推荐答案
C#有它自己的 的DateTime
结构。我们的目标是
C# has it's own DateTime
structure. The goal is to
- 您的字符串转换为
的DateTime
然后 - 转换您的
的DateTime
返回一个字符串。
- convert your string to a
DateTime
and then - convert your
DateTime
back to a string.
首先,你需要获得的格式字符串的两种格式的X和Y检查以下两个列表:
First, you need to get the format string for both formats X and Y. Check the following two lists:
- Standard Date and Time Format Strings
- Custom Date and Time Format Strings
例如,为 12/31/2015
,所有的<$ C $的C> D 或 MM / DD / YYYY
(使用EN-美国或固定区域性)或 MM\ / dd\ / YYYY
(任何区域)就可以了。对于 2015年12月31日00:00:00
,这将是 YYYY-MM-DD HH:MM:SS
。
E.g., for 12/31/2015
, all of d
or MM/dd/yyyy
(with the en-US or invariant culture) or MM\/dd\/yyyy
(with any locale) would be fine. For 2015-12-31 00:00:00
, it would be yyyy-MM-dd HH:mm:ss
.
有关的第一步,你可以使用的 DateTime.ParseExact (或的 DateTime.TryParseExact ,如果你想如果字符串不具有正确的格式,以正常失败),如:
For the first step, you can use DateTime.ParseExact (or DateTime.TryParseExact, if you want to fail gracefully if the string does not have the correct format), e.g.,
var myDateTime = DateTime.ParseExact(myInputString, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
有关第二步骤中,使用的则DateTime.ToString :
var myOutputString = myDateTime.ToString("yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture);
这篇关于我怎么能转换日期字符串格式,从X要格式化Y'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!