当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何解析DateTime并将其转换为RFC3339日期时间格式?》经验,为你挑选了2个好方法。

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



1> Matt Howells..:

您无需编写自己的转换代码.只是用

XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)

解析RFC-3339字符串,和

XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)

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

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


只是要补充一点,这个库可以很好地解析并将日期从谷歌日历事件转换为.NET日期时间

2> Oppositional..:

这是C#中如何解析和转换DateTime与RFC-3339表示之间的实现.唯一的限制是DateTime采用协调世界时(UTC).

using System;
using System.Globalization;

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

        //============================================================
        //  Public Properties
        //============================================================
        #region Rfc3339DateTimeFormat
        /// 
        /// Gets the custom format specifier that may be used to represent a  in the RFC 3339 format.
        /// 
        /// A DateTime format string that may be used to represent a  in the RFC 3339 format.
        /// 
        /// 
        /// This method returns a string representation of a  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  is a valid 
        /// date-time format string for use in the  method.
        /// 
        /// 
        public static string Rfc3339DateTimeFormat
        {
            get
            {
                return format;
            }
        }
        #endregion

        #region Rfc3339DateTimePatterns
        /// 
        /// Gets an array of the expected formats for RFC 3339 date-time string representations.
        /// 
        /// 
        /// An array of the expected formats for RFC 3339 date-time string representations 
        /// that may used in the  method.
        /// 
        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)
        /// 
        /// Converts the specified string representation of a date and time to its  equivalent.
        /// 
        /// A string containing a date and time to convert.
        /// A  equivalent to the date and time contained in .
        /// 
        /// The string  is parsed using formatting information in the  object.
        /// 
        ///  is a null reference (Nothing in Visual Basic).
        ///  does not contain a valid RFC 3339 string representation of a date and time.
        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)
        /// 
        /// Converts the value of the specified  object to its equivalent string representation.
        /// 
        /// The Coordinated Universal Time (UTC)  to convert.
        /// A RFC 3339 string representation of the value of the .
        /// 
        /// 
        /// This method returns a string representation of the  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.
        /// 
        /// 
        /// 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.
        /// 
        /// 
        /// The specified  object does not represent a Coordinated Universal Time (UTC) value.
        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)
        /// 
        /// Converts the specified string representation of a date and time to its  equivalent.
        /// 
        /// A string containing a date and time to convert.
        /// 
        /// When this method returns, contains the  value equivalent to the date and time 
        /// contained in , if the conversion succeeded, 
        /// or MinValue 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.
        /// 
        /// true if the  parameter was converted successfully; otherwise, false.
        /// 
        /// The string  is parsed using formatting information in the  object.
        /// 
        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
    }
}


为什么要为BCL中已有的东西编写这段代码呢?
在这里必须同意马特.RFC3339不是由其中一种DateTime.ToString标准格式提供的 - 这是令人惊讶的 - 但是XmlConvert完成了这项工作.例如,我使用XmlConvert.ToString(value,XmlDateTimeSerializationMode.Utc)
感谢您这样做,如果您使用的是.NET Core,则无法使用XmlConvert。
推荐阅读
pan2502851807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有