Comment puis-je convertir une structure DateTime en sa représentation sous forme de chaîne RFC 3339 équivalente et/ou analyser cette représentation sous forme de chaîne à une structure DateTime? Le format date-heure RFC-3339 est utilisé dans un certain nombre de spécifications telles que Atom Syndication Format.Comment est-ce que j'analyse et convertis un DateTime au format date-heure de RFC 3339?
Répondre
Ceci est une implémentation en C# de la façon d'analyser et de convertir un DateTime vers et depuis sa représentation RFC-3339. La seule restriction est que le DateTime est en temps universel coordonné (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
}
}
Dans .NET (en supposant UTC):
datetime.ToString("YYYY-MM-DD'T'HH:mm:ssZ")
DateTime.Parse()
peut être utilisé pour se reconvertir dans une structure DateTime
.
Ne pensez pas que "AAAA-MM-JJ'T'HH: mm: ss" peut être correct; il n'a pas de décalage par rapport à UTC, ni 'Z' (= décalage d'origine par rapport à UTC). –
Cela n'a pas fonctionné pour moi. J'ai dû utiliser 'datetime.ToUniversalTime(). ToString (" aaaa-MM-jj'H'HH: mm: ssZ ")' –
Cela fonctionne uniquement lorsque le DateTime est dans le fuseau horaire UTC (_universal time_). –
Vous n'avez pas besoin d'écrire votre propre code de conversion. Il suffit d'utiliser
XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)
pour analyser une chaîne de RFC-3339, et
XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)
convertir un datetime (UTC) à une chaîne.
Réf.
http://msdn.microsoft.com/en-us/library/ms162342(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/ms162344(v=vs.110).aspx
Juste pour ajouter que cette bibliothèque fonctionne très bien l'analyse et la conversion des dates d'événements google calendar vers/depuis .NET Datetime –
Une équation simple sera en mesure d'obtenir le résultat que vous êtes après:
rfcFormat = DateDiff("s", "1/1/1970", Now())
- 1. DateHeure, DateHeure? et LINQ
- 2. RDLC-Report et CultureInfo au format Datetime
- 3. Format de message POP3 rfc
- 4. Quelle est la différence entre les formats de date ISO 8601 et RFC 3339?
- 5. dateheure fonction dans php
- 6. XSLT transformation datetime au format date
- 7. LinqDataSource et le format DateTime
- 8. Arrondi des objets DateHeure
- 9. comment valider le format datetime
- 10. Comment définir un format DateTime global dans un projet ASP.NET?
- 11. Comment est-ce que je peux convertir un datetime au format de date de jj-mmm-aaaa?
- 12. DateTime Hex Format
- 13. DateTime format hexadécimal
- 14. DateTime Format en C#
- 15. Format RSS pubDate en tant que .NET DateTime
- 16. Format WPF DateTime dans TextBlock?
- 17. Comment convertir un datetime mysql en PHP au format m/d/y?
- 18. Comment obtenir la date du format datetime
- 19. Comment écrire un bon standard RFC et par où commencer?
- 20. ASP.NET AJAX et le format DateTime sur le client
- 21. RFC 1123 Représentation de date en Python?
- 22. Sql Server DATETIME format incorrrect
- 23. Sérialisation de l'objet au format JSON et obtention du format
- 24. Comment convertir la date dans la zone de texte au format MySQL DATETIME
- 25. Format DateTime sur le serveur d'hébergement
- 26. Comment modifier le format de tri universel DateTime dans .NET?
- 27. PHP: format de numéro au format local
- 28. Chaîne au format d'heure mais comment?
- 29. SPListItem.Properties Les champs DateTime sont dans un format Hex bizarre
- 30. Définir le format DateTime par défaut C#
Pourquoi vouloir écrire ce code pour quelque chose qui est déjà dans la BCL? –
Je suis d'accord avec Matt ici. RFC3339 n'est pas pris en charge par l'un des formats standard DateTime.ToString - ce qui est surprenant - mais XmlConvert fait le travail. Par exemple. J'utilise XmlConvert.ToString (value, XmlDateTimeSerializationMode.Utc) –
Commentaires saints, batman! –