¿Cómo convierto una estructura DateTime a su representación de cadena formateada RFC 3339 equivalente y/o analizo esta representación de cadena de nuevo a una estructura DateTime? El formato de fecha y hora RFC-3339 se utiliza en una serie de especificaciones como Atom Syndication Format.¿Cómo analizo y convierto un DateTime al formato de fecha y hora RFC 3339?
Respuesta
Esta es una implementación en C# de cómo analizar y convertir un DateTime desde y hacia su representación RFC-3339. La única restricción que tiene es que DateTime está en hora universal coordinada (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
}
}
En .NET (suponiendo UTC):
datetime.ToString("YYYY-MM-DD'T'HH:mm:ssZ")
DateTime.Parse()
se puede utilizar para convertir de nuevo en una estructura DateTime
.
No crea "YYYY-MM-DD'T'HH: mm: ss" puede ser correcto; no tiene desplazamiento de UTC, ni 'Z' (= desplazamiento de cero desde UTC). –
Esto no funcionó para mí. Tuve que usar 'datetime.ToUniversalTime(). ToString (" aaaa-MM-dd'T'HH: mm: ssZ ")' –
Solo funciona cuando DateTime se encuentra en la zona horaria UTC (_universal time_). –
No necesita escribir su propio código de conversión. Sólo tiene que utilizar
XmlConvert.ToDateTime(string s, XmlDateTimeSerializationMode dateTimeOption)
a analizar una cadena RFC-3339, y
XmlConvert.ToString(DateTime value, XmlDateTimeSerializationMode dateTimeOption)
para convertir una fecha y hora (UTC) en una cadena.
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
Solo para agregar que esta biblioteca funciona bien analizando y convirtiendo fechas de eventos de calendario de Google a/desde .NET Datetime –
Una ecuación simple será capaz de obtener el resultado que está buscando:
rfcFormat = DateDiff("s", "1/1/1970", Now())
- 1. ¿Cómo analizo y convierto DateTime al formato de fecha y hora RFC 822?
- 2. Formato Excepción: fecha y hora
- 3. ¿Formato de fecha y hora de la cadena?
- 4. Formato de fecha y hora para un mes y año
- 5. Formato de fecha y hora
- 6. Conversión de un formato de fecha personalizado (cadena) a una fecha y hora
- 7. ¿Cómo convierto un objeto DateTime al formato YYMMDD?
- 8. Al almacenar una fecha y hora en el servidor sql (tipo de fecha y hora), ¿en qué formato lo almacena?
- 9. convertido strtotime al formato de fecha y hora en php
- 10. ¿Cuál es la diferencia entre los formatos de fecha ISO 8601 y RFC 3339?
- 11. Cómo separar FECHA y HORA desde DATETIME en MySQL
- 12. Cambio de formato de fecha y hora en formato numérico
- 13. Conversión de fecha y hora a hora POSIX
- 14. RFC 3339 Marca de tiempo de salida en Java
- 15. Cadena de formato a fecha y hora con zona horaria
- 16. Cómo analizar una fecha/hora de RFC 2822 en un horario de Python?
- 17. formato y visualización de fecha y hora en XSLT
- 18. Convertir la hora local (número de 10 dígitos) en un formato de fecha y hora legible
- 19. Rails 3 DateTime y hora formato beginning_of_day end_of_day incorrecta
- 20. convertir hora utc y desplazamiento a DateTime
- 21. ¿Cómo convierto DateTime .NET datatype a W3C XML DateTime data type string y viceversa?
- 22. Unir fecha y hora con DateTime en C#
- 23. Insertar fecha actual en formato de fecha y hora mySQL
- 24. Combina la fecha y la hora cuando la fecha es un DateTime y la hora es una cadena
- 25. cómo dar formato de fecha y hora átomo de
- 26. Entity Framework - MySQL - Número de formato de fecha y hora
- 27. ¿Cómo restar una fecha y hora de otra fecha y hora?
- 28. ¿Cómo obtener el formato de sistema de fecha y hora?
- 29. JSON de fecha y hora cuestión
- 30. git: zona horaria y la fecha y hora formato
Por qué se molestan en escribir el código para algo que ya está en el BCL? –
Tengo que estar de acuerdo con Matt aquí. RFC3339 no es atendido por uno de los formatos estándar DateTime.ToString, lo que es sorprendente, pero XmlConvert hace el trabajo. P.ej. Yo uso XmlConvert.ToString (value, XmlDateTimeSerializationMode.Utc) –
¡Santos comentarios, batman! –