关于.net:如何解析DateTime并将其转换为RFC 3339日期时间格式?

关于.net:如何解析DateTime并将其转换为RFC 3339日期时间格式?

How do I parse and convert a DateTime to the RFC 3339 date-time format?

如何将DateTime结构转换为其等效的RFC 3339格式的字符串表示形式和/或将此字符串表示形式解析回DateTime结构? RFC-3339日期时间格式用于许多规范中,例如Atom联合组织格式。


您无需编写自己的转换代码。 只需使用

1
XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)

解析RFC-3339字符串,以及

1
XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)

将(UTC)日期时间转换为字符串。

参考
http://msdn.microsoft.com/zh-CN/library/ms162342(v=vs.110).aspx
http://msdn.microsoft.com/zh-CN/library/ms162344(v=vs.110).aspx


这是C#中关于如何解析和转换DateTime与其RFC-3339表示形式之间的转换的实现。 它唯一的限制是DateTime以协调世界时(UTC)为单位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using System;
using System.Globalization;

namespace DateTimeConsoleApplication
{
    /// <summary>
    /// Provides methods for converting <see cref="DateTime"/> structures to and from the equivalent RFC 3339 string representation.
    /// </summary>
    public static class Rfc3339DateTime
    {
        //============================================================
        //  Private members
        //============================================================
        #region Private Members
        /// <summary>
        /// Private member to hold array of formats that RFC 3339 date-time representations conform to.
        /// </summary>
        private static string[] formats = new string[0];
        /// <summary>
        /// Private member to hold the DateTime format string for representing a DateTime in the RFC 3339 format.
        /// </summary>
        private const string format ="yyyy-MM-dd'T'HH:mm:ss.fffK";
        #endregion

        //============================================================
        //  Public Properties
        //============================================================
        #region Rfc3339DateTimeFormat
        /// <summary>
        /// Gets the custom format specifier that may be used to represent a <see cref="DateTime"/> in the RFC 3339 format.
        /// </summary>
        /// <value>A DateTime format string that may be used to represent a <see cref="DateTime"/> in the RFC 3339 format.</value>
        /// <remarks>
        /// <para>
        /// This method returns a string representation of a <see cref="DateTime"/> that
        /// is precise to the three most significant digits of the seconds fraction; that is, it represents
        /// the milliseconds in a date and time value. The <see cref="Rfc3339DateTimeFormat"/> is a valid
        /// date-time format string for use in the <see cref="DateTime.ToString(String, IFormatProvider)"/> method.
        /// </para>
        /// </remarks>
        public static string Rfc3339DateTimeFormat
        {
            get
            {
                return format;
            }
        }
        #endregion

        #region Rfc3339DateTimePatterns
        /// <summary>
        /// Gets an array of the expected formats for RFC 3339 date-time string representations.
        /// </summary>
        /// <value>
        /// An array of the expected formats for RFC 3339 date-time string representations
        /// that may used in the <see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/> method.
        /// </value>
        public static string[] Rfc3339DateTimePatterns
        {
            get
            {
                if (formats.Length > 0)
                {
                    return formats;
                }
                else
                {
                    formats = new string[11];

                    // Rfc3339DateTimePatterns
                    formats[0] ="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK";
                    formats[1] ="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK";
                    formats[2] ="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK";
                    formats[3] ="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK";
                    formats[4] ="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK";
                    formats[5] ="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK";
                    formats[6] ="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK";
                    formats[7] ="yyyy'-'MM'-'dd'T'HH':'mm':'ssK";

                    // Fall back patterns
                    formats[8] ="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; // RoundtripDateTimePattern
                    formats[9] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;
                    formats[10] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;

                    return formats;
                }
            }
        }
        #endregion

        //============================================================
        //  Public Methods
        //============================================================
        #region Parse(string s)
        /// <summary>
        /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
        /// </summary>
        /// <param name="s">A string containing a date and time to convert.</param>
        /// <returns>A <see cref="DateTime"/> equivalent to the date and time contained in <paramref name="s"/>.</returns>
        /// <remarks>
        /// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
        /// </remarks>
        /// <exception cref="ArgumentNullException"><paramref name="s"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="FormatException"><paramref name="s"/> does not contain a valid RFC 3339 string representation of a date and time.</exception>
        public static DateTime Parse(string s)
        {
            //------------------------------------------------------------
            //  Validate parameter
            //------------------------------------------------------------
            if(s == null)
            {
                throw new ArgumentNullException("s");
            }

            DateTime result;
            if (Rfc3339DateTime.TryParse(s, out result))
            {
                return result;
            }
            else
            {
                throw new FormatException(String.Format(null,"{0} is not a valid RFC 3339 string representation of a date and time.", s));
            }
        }
        #endregion

        #region ToString(DateTime utcDateTime)
        /// <summary>
        /// Converts the value of the specified <see cref="DateTime"/> object to its equivalent string representation.
        /// </summary>
        /// <param name="utcDateTime">The Coordinated Universal Time (UTC) <see cref="DateTime"/> to convert.</param>
        /// <returns>A RFC 3339 string representation of the value of the <paramref name="utcDateTime"/>.</returns>
        /// <remarks>
        /// <para>
        /// This method returns a string representation of the <paramref name="utcDateTime"/> that
        /// is precise to the three most significant digits of the seconds fraction; that is, it represents
        /// the milliseconds in a date and time value.
        /// </para>
        /// <para>
        /// While it is possible to display higher precision fractions of a second component of a time value,
        /// that value may not be meaningful. The precision of date and time values depends on the resolution
        /// of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's
        /// resolution is approximately 10-15 milliseconds.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentException">The specified <paramref name="utcDateTime"/> object does not represent a <see cref="DateTimeKind.Utc">Coordinated Universal Time (UTC)</see> value.</exception>
        public static string ToString(DateTime utcDateTime)
        {
            if (utcDateTime.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("utcDateTime");
            }

            return utcDateTime.ToString(Rfc3339DateTime.Rfc3339DateTimeFormat, DateTimeFormatInfo.InvariantInfo);
        }
        #endregion

        #region TryParse(string s, out DateTime result)
        /// <summary>
        /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
        /// </summary>
        /// <param name="s">A string containing a date and time to convert.</param>
        /// <param name="result">
        /// When this method returns, contains the <see cref="DateTime"/> value equivalent to the date and time
        /// contained in <paramref name="s"/>, if the conversion succeeded,
        /// or <see cref="DateTime.MinValue">MinValue</see> if the conversion failed.
        /// The conversion fails if the s parameter is a null reference (Nothing in Visual Basic),
        /// or does not contain a valid string representation of a date and time.
        /// This parameter is passed uninitialized.
        /// </param>
        /// <returns>true if the <paramref name="s"/> parameter was converted successfully; otherwise, false.</returns>
        /// <remarks>
        /// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
        /// </remarks>
        public static bool TryParse(string s, out DateTime result)
        {
            //------------------------------------------------------------
            //  Attempt to convert string representation
            //------------------------------------------------------------
            bool wasConverted   = false;
            result              = DateTime.MinValue;

            if (!String.IsNullOrEmpty(s))
            {
                DateTime parseResult;
                if (DateTime.TryParseExact(s, Rfc3339DateTime.Rfc3339DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))
                {
                    result          = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);
                    wasConverted    = true;
                }
            }

            return wasConverted;
        }
        #endregion
    }
}


在.NET(假设UTC)中:

1
 datetime.ToString("YYYY-MM-DD'T'HH:mm:ssZ")

DateTime.Parse()可用于转换回DateTime结构。


一个简单的方程式就能得到您想要的结果:

1
rfcFormat = DateDiff("s","1/1/1970", Now())


推荐阅读