Wie konvertiere ich eine DateTime-Struktur in die entsprechende formatierte Zeichenfolgendarstellung RFC 3339 und/oder analysiere diese Zeichenfolgendarstellung zurück zu einer Struktur DateTime? Das Datum-Uhrzeit-Format RFC-3339 wird in einer Reihe von Spezifikationen wie dem Atom Syndication Format verwendet.Wie analysiere und konvertiere ich eine DateTime in das RFC 3339-Format?
Antwort
Dies ist eine Implementierung in C# zum Analysieren und Konvertieren einer DateTime zu und von ihrer RFC-3339-Darstellung. Die einzige Einschränkung ist, dass die DateTime in Coordinated Universal Time (UTC) ist.
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
}
}
In .NET (vorausgesetzt, UTC):
datetime.ToString("YYYY-MM-DD'T'HH:mm:ssZ")
DateTime.Parse()
kann wieder in eine DateTime
Struktur konvertiert werden.
Denke nicht, "YYYY-MM-DD'T'HH: mm: ss" kann richtig sein; es hat keinen Offset von UTC, noch 'Z' (= Null-Offset von UTC). –
Das hat bei mir nicht funktioniert. Ich musste 'datetime.ToUniversalTime() verwenden. ToString (" yyyy-MM-dd'T'HH: mm: ssZ ")' –
Es funktioniert nur, wenn die DateTime in der UTC-Zeitzone (_universal time_) ist. –
Sie müssen keinen eigenen Konvertierungscode schreiben. Verwenden Sie einfach
XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)
eine RFC-3339 Zeichenfolge zu analysieren, und
XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)
ein (UTC) Datetime in eine Zeichenfolge zu konvertieren.
Ref.-Nr.
http://msdn.microsoft.com/en-us/library/ms162342(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/ms162344(v=vs.110).aspx
Um nur hinzuzufügen, dass diese Bibliothek funktioniert gut analysieren und Konvertieren von Daten aus Google Kalenderereignisse zu/von .NET Datetime –
Eine einfache Gleichung wird in der Lage das Ergebnis sind Sie nach erhalten:
rfcFormat = DateDiff("s", "1/1/1970", Now())
- 1. Wie analysiere und konvertiere ich DateTime in das RFC-822-Datum/Uhrzeit-Format?
- 2. Wie konvertiere ich ein DateTime-Objekt in das YYMMDD-Format?
- 3. Wo kann ich RFC- und ISO-Datetime-Formate durchsuchen?
- 4. Wie konvertiere ich diese JSON Datetime?
- 5. Wie konvertiere ich Datetime zu Timestamp Epoch
- 6. Convert Python datetime in RFC 2822
- 7. Wie analysiere ich das JSON-Datumsformat in Perl?
- 8. Konvertiere MySQL datetime in timestamp
- 9. Wie lese und analysiere ich eine .dat-Datei in C?
- 10. Wie konvertiere ich RFC822 in ein Python-Datetime-Objekt?
- 11. Konvertiere datetime in nvarchar, behalte aber das Format
- 12. Konvertiere eine Varchar-Variable in eine Datetime-Variable
- 13. Wie konvertiere ich eine Datetime mit Millisekunden in eine Zeichenfolge in C#?
- 14. Wie analysiere ich eine dtd-Datei
- 15. Wie analysiere ich eine JSON-Datei?
- 16. Wie analysiere ich eine .mdmp Datei?
- 17. Wie analysiere ich eine YAML-Datei?
- 18. Konvertiere String 'time' in ein Datetime
- 19. Konvertiere MySQL Datetime in C++ Std :: time_t
- 20. Wie analysiere ich eine .hprof Datei?
- 21. Wie konvertiere ich Benutzereingaben in eine Liste?
- 22. Wie konvertiere ich NaN in eine 0?
- 23. Wie konvertiere ich ein Datetime-Feld in eine formatierte Zeichenfolge in SQL Server 2005?
- 24. Wie analysiere ich das Datum von der Befehlszeile in Solaris?
- 25. Wie analysiere ich ein Datum mit Millisekunden?
- 26. Wie konvertiere ich eine Zeichenfolge in eine Liste in Io?
- 27. Wie analysiert man RFC 2822 Datum/Zeit in eine Python Datetime?
- 28. Wie konvertiere ich eine Zeichenfolge wie "Red" in eine System.Windows.Media.Color?
- 29. Wie analysiere ich eine Excel-Datei in JavaScript?
- 30. Wie analysiere ich eine serialisierte PHP-Datenstruktur in Java?
Warum sich die Mühe diesen Code für etwas zu schreiben, die bereits in der BCL ist? –
Muss hier mit Matt übereinstimmen. RFC3339 wird von keinem der DateTime.ToString-Standardformate berücksichtigt - was überraschend ist - aber XmlConvert erledigt die Aufgabe. Z.B. Ich benutze XmlConvert.ToString (Wert, XmlDateTimeSerializationMode.Utc) –
Heilige Kommentare, Batman! –