Làm cách nào để chuyển đổi cấu trúc DateTime thành tương đương RFC 3339 biểu diễn chuỗi được định dạng và/hoặc phân tích cú pháp biểu diễn chuỗi này về cấu trúc DateTime? Định dạng ngày giờ RFC-3339 được sử dụng trong một số thông số kỹ thuật như Atom Syndication Format.Làm cách nào để phân tích cú pháp và chuyển đổi một DateTime thành định dạng ngày giờ RFC 3339?
Trả lời
Đây là triển khai trong C# về cách phân tích cú pháp và chuyển đổi một DateTime đến và từ đại diện RFC-3339 của nó. Hạn chế duy nhất mà nó có là DateTime là trong giờ phối hợp quốc tế (UTC).
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 <i>DateTime format string</i> 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 <b>null</b> 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 <b>null</b> 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><b>true</b> if the <paramref name="s"/> parameter was converted successfully; otherwise, <b>false</b>.</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
}
}
Trong NET (giả sử UTC):
datetime.ToString("YYYY-MM-DD'T'HH:mm:ssZ")
DateTime.Parse()
thể được sử dụng để chuyển đổi trở lại thành một cấu trúc DateTime
.
Đừng nghĩ "YYYY-MM-DD'T'HH: mm: ss" có thể đúng; nó không có bù đắp từ UTC, cũng không 'Z' (= số không bù đắp từ UTC). –
Điều này không hiệu quả đối với tôi. Tôi đã phải sử dụng 'datetime.ToUniversalTime(). ToString (" yyyy-MM-dd'T'HH: mm: ssZ ")' –
Nó chỉ hoạt động khi DateTime nằm trong múi giờ UTC (_universal time_). –
Bạn không cần phải viết mã chuyển đổi của riêng mình. Chỉ cần sử dụng
XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)
để phân tích một chuỗi RFC-3339, và
XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)
để chuyển đổi một (UTC) datetime thành một chuỗi.
Ref.
http://msdn.microsoft.com/en-us/library/ms162342(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/ms162344(v=vs.110).aspx
Chỉ cần thêm rằng thư viện này hoạt động phân tích cú pháp tốt và chuyển đổi ngày từ các sự kiện lịch google sang/từ. –
Một phương trình đơn giản sẽ có thể để có được những kết quả mà bạn đang theo đuổi:
rfcFormat = DateDiff("s", "1/1/1970", Now())
- 1. Làm thế nào để phân tích ngày/giờ RFC 2822 thành một datetime Python?
- 2. C# Ngày giờ Phân tích cú pháp/chuyển đổi định dạng này "20120314T130000"
- 3. Phân tích cú pháp cột Gấu trúc thành Ngày giờ
- 4. Phân tích cú pháp ngày RFC 822 với NSDateFormatter
- 5. Phân tích cú pháp C# datetime thành datetime javascript
- 6. Làm cách nào để phân tích ngày và chuyển đổi múi giờ trong Perl?
- 7. Ngày/giờ phân tích cú pháp trong C++ (Mọi chuỗi định dạng thành Epoch)
- 8. Phân tích cú pháp ngày RFC 2822 trong JAVA
- 9. Chuyển đổi thời gian RFC 3339 thành dấu thời gian chuẩn của Python
- 10. Ngày phân tích cú pháp với Joda với múi giờ
- 11. Chuyển đổi C# DateTime thành Ngày Javascript
- 12. làm thế nào để chuyển đổi một ngày chuỗi thành định dạng datetime trong python?
- 13. Ngày phân tích cú pháp trong MySQL
- 14. Phân tích định dạng ngày giờ tùy chỉnh
- 15. Chuỗi ngày phân tích cú pháp và định dạng thay đổi
- 16. Phân tích cú pháp một chuỗi thành định dạng "năm-tháng-ngày" trong C#
- 17. C# phân tích bất kỳ chuỗi định dạng ngày nào sang ngày giờ
- 18. Chuỗi định dạng phân tích cú pháp
- 19. Chuyển đổi chuỗi định dạng dd/mm/yyyy thành Ngày giờ
- 20. Chuyển đổi định dạng ngày tùy chỉnh (chuỗi) thành ngày giờ
- 21. Ngày phân tích cú pháp trong Bash
- 22. Chuyển đổi ngày giờ thành định dạng được chỉ định
- 23. Thư viện C để phân tích cú pháp Ngày giờ
- 24. Phân tích cú pháp thông tin ngày JSON thành C# DateTime
- 25. Sự khác nhau giữa định dạng ngày tháng ISO 8601 và RFC 3339 là gì?
- 26. Cần phân tích cú pháp dd.MM.yyyy thành Ngày giờ bằng cách sử dụng TryParse
- 27. Ngày giờ chuyển đổi XSLT sang định dạng ngày
- 28. Làm thế nào tôi có thể phân tích cú pháp một chuỗi thiếu dấu phân cách thành DateTime bằng C#?
- 29. Phân tích chuỗi ngày giờ
- 30. Chuỗi phân tích cú pháp thành TimeSpan
Tại sao bận tâm để viết mã này kiếm cái gì đó là đã có trong BCL? –
Phải đồng ý với Matt ở đây. RFC3339 không được cung cấp bởi một trong các định dạng chuẩn DateTime.ToString - điều này thật đáng ngạc nhiên - nhưng XmlConvert thực hiện công việc. Ví dụ. Tôi sử dụng XmlConvert.ToString (giá trị, XmlDateTimeSerializationMode.Utc) –
Bình luận của Holy, batman! –