DateTime Estructura
Definición
Representa un instante de tiempo, normalmente expresado en forma de fecha y hora del día.Represents an instant in time, typically expressed as a date and time of day.
public value class DateTime : IComparable, IComparable<DateTime>, IConvertible, IEquatable<DateTime>, IFormattable
public value class DateTime : IComparable, IComparable<DateTime>, IConvertible, IEquatable<DateTime>, IFormattable, System::Runtime::Serialization::ISerializable
public value class DateTime : IComparable, IConvertible, IFormattable
public value class DateTime : IComparable, IComparable<DateTime>, IEquatable<DateTime>, IFormattable
public struct DateTime : IComparable, IComparable<DateTime>, IConvertible, IEquatable<DateTime>, IFormattable
public struct DateTime : IComparable, IComparable<DateTime>, IConvertible, IEquatable<DateTime>, IFormattable, System.Runtime.Serialization.ISerializable
[System.Serializable]
public struct DateTime : IComparable, IConvertible, IFormattable
[System.Serializable]
public struct DateTime : IComparable, IComparable<DateTime>, IConvertible, IEquatable<DateTime>, IFormattable, System.Runtime.Serialization.ISerializable
public struct DateTime : IComparable, IComparable<DateTime>, IEquatable<DateTime>, IFormattable
type DateTime = struct
interface IConvertible
interface IFormattable
type DateTime = struct
interface IConvertible
interface IFormattable
interface ISerializable
[<System.Serializable>]
type DateTime = struct
interface IFormattable
interface IConvertible
[<System.Serializable>]
type DateTime = struct
interface IFormattable
interface IConvertible
interface ISerializable
type DateTime = struct
interface IFormattable
Public Structure DateTime
Implements IComparable, IComparable(Of DateTime), IConvertible, IEquatable(Of DateTime), IFormattable
Public Structure DateTime
Implements IComparable, IComparable(Of DateTime), IConvertible, IEquatable(Of DateTime), IFormattable, ISerializable
Public Structure DateTime
Implements IComparable, IConvertible, IFormattable
Public Structure DateTime
Implements IComparable, IComparable(Of DateTime), IEquatable(Of DateTime), IFormattable
- Herencia
- Atributos
- Implementaciones
Comentarios
Importante
Las eras en los calendarios japoneses se basan en el reino del emperador y, por tanto, se espera que cambien.Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. Por ejemplo, el 1 de mayo de 2019 marcaba el comienzo de la era Reiwa en JapaneseCalendar y JapaneseLunisolarCalendar.For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. Este cambio de era afecta a todas las aplicaciones que usan estos calendarios.Such a change of era affects all applications that use these calendars. Para obtener más información y determinar si sus aplicaciones están entre las afectadas, consulte Handling a new era in the Japanese calendar in .NET (Gestión de una nueva era del calendario japonés en .NET).See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. Para obtener más información sobre cómo probar aplicaciones en sistemas Windows para garantizar que estén preparadas para el cambio de era, consulte Prepare your application for the Japanese era change (Preparación de la aplicación para el cambio de era japonesa).See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. Consulte Trabajar con eras para ver las características de .NET que admiten calendarios con varias eras y procedimientos recomendados al trabajar con calendarios que admiten varias eras.See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.
Vínculos rápidos a código de ejemploQuick links to example code
Nota
Algunos ejemplos de C# de este artículo se ejecutan en el ejecutor de código en línea y área de juegos de Try.NET.Some C# examples in this article run in the Try.NET inline code runner and playground. Haga clic en el botón Ejecutar para ejecutar un ejemplo en una ventana interactiva.Select the Run button to run an example in an interactive window. Una vez que se ejecuta el código, puede modificar y ejecutar el código modificado si vuelve a hacer clic en Ejecutar.Once you execute the code, you can modify it and run the modified code by selecting Run again. El código modificado se ejecuta en la ventana interactiva o, si se produce un error en la compilación, en la ventana interactiva se muestran todos los mensajes de error del compilador de C#.The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.
La zona horaria local del ejecutor de código en línea de Try.NET y del área de juegos es la hora universal coordinada o UTC.The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. Esto puede afectar al comportamiento y la salida de ejemplos que ilustran los tipos DateTime, DateTimeOffset y TimeZoneInfo y sus miembros.This may affect the behavior and the output of examples that illustrate the DateTime, DateTimeOffset, and TimeZoneInfo types and their members.
En este artículo se incluyen varios ejemplos que usan el DateTime tipo:This article includes several examples that use the DateTime type:
Ejemplos de inicializaciónInitialization Examples
- Invocar un constructorInvoke a constructor
- Invocar el constructor sin parámetros implícitoInvoke the implicit parameterless constructor
- Asignación de un valor devueltoAssignment from return value
- Analizar una cadena que representa una fecha y horaParsing a string that represents a date and time
- Visual Basic sintaxis para inicializar una fecha y horaVisual Basic syntax to initialize a date and time
Aplicar formato a los DateTime objetos como cadenasFormatting DateTime objects as strings
- Usar el formato de fecha y hora predeterminadoUse the default date time format
- Dar formato a una fecha y hora mediante una referencia cultural específicaFormat a date and time using a specific culture
- Dar formato a una fecha y hora mediante una cadena de formato estándar o personalizadoFormat a date time using a standard or custom format string
- Especificar una cadena de formato y una referencia cultural específicaSpecify both a format string and a specific culture
- Dar formato a una fecha y hora mediante el estándar ISO 8601 para servicios WebFormat a date time using the ISO 8601 standard for web services
Analizar cadenas como DateTime objetosParsing strings as DateTime objects
- Use
ParseoTryParsepara convertir una cadena en una fecha y horaUseParseorTryParseto convert a string to a date and time - Use
ParseExactoTryParseExactpara convertir una cadena en un formato conocido.UseParseExactorTryParseExactto convert a string in a known format - Convertir la representación de cadena ISO 8601 en una fecha y horaConvert from the ISO 8601 string representation to a date and time
DateTime traducciónDateTime resolution
- Explorar la resolución de valores de fecha y horaExplore the resolution of date and time values
- Comparar la igualdad dentro de una toleranciaComparing for equality within a tolerance
Referencia cultural y calendariosCulture and calendars
- Mostrar valores de fecha y hora mediante calendarios específicos de la referencia culturalDisplay date and time values using culture specific calendars
- Analizar cadenas según un calendario específico de la referencia culturalParse strings according to a culture specific calendar
- Inicializar una fecha y hora desde el calendario de una referencia cultural específicaInitialize a date and time from a specific culture's calendar
- Obtener acceso a las propiedades de fecha y hora mediante el calendario de una referencia cultural específicaAccessing date and time properties using a specific culture's calendar
- Recuperar la semana del año usando calendarios específicos de la referencia culturalRetrieving the week of the year using culture specific calendars
PersistenciaPersistence
- Conservar valores de fecha y hora como cadenas en la zona horaria localPersisting date and time values as strings in the local time zone
- Conservar valores de fecha y hora como cadenas en un formato invariable de hora y referencia culturalPersisting date and time values as strings in a culture and time invariant format
- Conservar valores de fecha y hora como enterosPersisting date and time values as integers
- Conservar valores de fecha y hora mediante el
XmlSerializerPersisting date and time values using theXmlSerializer - Conservar valores de fecha y hora mediante el
BinaryFormatterPersisting date and time values using theBinaryFormatter - Conservar valores de fecha y hora con datos de zona horariaPersisting date and time values with time zone data
Vínculos rápidos a temas de notas.Quick links to Remarks topics.
Esta sección contiene temas para muchos usos comunes del DateTime struct:This section contains topics for many common uses of the DateTime struct:
- Inicializar un
DateTimeobjetoInitializing aDateTimeobject - Valores DateTime y sus representaciones de cadenaDateTime values and their string representations
- Analizar valores DateTime de cadenasParsing DateTime values from strings
- Valores DateTimeDateTime values
- Operaciones DateTimeDateTime operations
- Resolución de DateTimeDateTime resolution
- Valores de DateTime y calendariosDateTime values and calendars
- Conservar valores de fecha y horaPersisting DateTime values
- DateTime frente a TimeSpanDateTime vs. TimeSpan
- Comparar la igualdad dentro de la toleranciaComparing for equality within tolerance
- Consideraciones sobre la interoperabilidad COMCOM interop considerations
El DateTime tipo de valor representa las fechas y horas con valores comprendidos entre 00:00:00 (medianoche), 1 de enero de 0001 Anno Domini (era común) hasta 11:59:59 P.M., 31 de diciembre de 9999 d.c.The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (D.C) en el calendario gregoriano.(C.E.) in the Gregorian calendar.
Los valores de hora se miden en unidades 100-nanosegundos denominadas TICs.Time values are measured in 100-nanosecond units called ticks. Una fecha determinada es el número de TICs desde 12:00 de la medianoche del 1 de enero de 0001 D.C.A particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. era cristiana en el GregorianCalendar calendario.(C.E.) in the GregorianCalendar calendar. El número excluye los tics que se agregarían en segundos bisiestos.The number excludes ticks that would be added by leap seconds. Por ejemplo, un valor de ticks de 31241376000000000L representa la fecha viernes, 1 de enero de 0100 12:00:00 de la medianoche.For example, a ticks value of 31241376000000000L represents the date Friday, January 01, 0100 12:00:00 midnight. Un DateTime valor siempre se expresa en el contexto de un calendario explícito o predeterminado.A DateTime value is always expressed in the context of an explicit or default calendar.
Nota
Si está trabajando con un valor de TICs que desea convertir en otro intervalo de tiempo, como minutos o segundos, debe usar la constante,,, TimeSpan.TicksPerDay TimeSpan.TicksPerHour TimeSpan.TicksPerMinute TimeSpan.TicksPerSecond o TimeSpan.TicksPerMillisecond para realizar la conversión.If you are working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the TimeSpan.TicksPerDay, TimeSpan.TicksPerHour, TimeSpan.TicksPerMinute, TimeSpan.TicksPerSecond, or TimeSpan.TicksPerMillisecond constant to perform the conversion. Por ejemplo, para agregar el número de segundos representados por un número especificado de pasos al Second componente de un DateTime valor, puede usar la expresión dateValue.Second + nTicks/Timespan.TicksPerSecond .For example, to add the number of seconds represented by a specified number of ticks to the Second component of a DateTime value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.
Puede ver el código fuente de todo el conjunto de ejemplos de este artículo en Visual Basic o C# desde el repositorio de documentos en github.You can view the source for the entire set of examples from this article in either Visual Basic or C# from the docs repository on GitHub.
Nota
Una alternativa a la DateTime estructura para trabajar con valores de fecha y hora en zonas horarias concretas es la DateTimeOffset estructura.An alternative to the DateTime structure for working with date and time values in particular time zones is the DateTimeOffset structure. La DateTimeOffset estructura almacena la información de fecha y hora en un DateTime campo privado y el número de minutos que esa fecha y hora difieren de la hora UTC en un Int16 campo privado.The DateTimeOffset structure stores date and time information in a private DateTime field and the number of minutes by which that date and time differs from UTC in a private Int16 field. Esto hace posible que un DateTimeOffset valor refleje la hora en una zona horaria determinada, mientras que un DateTime valor solo puede reflejar de forma inequívoca la hora UTC y la hora de la zona horaria local.This makes it possible for a DateTimeOffset value to reflect the time in a particular time zone, whereas a DateTime value can unambiguously reflect only UTC and the local time zone's time. Para obtener una explicación sobre Cuándo usar la DateTime estructura o la DateTimeOffset estructura al trabajar con valores de fecha y hora, vea elegir entre DateTime, DateTimeOffset, TimeSpan y TimeZoneInfo.For a discussion about when to use the DateTime structure or the DateTimeOffset structure when working with date and time values, see Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo.
Inicializar un objeto DateTimeInitializing a DateTime object
Puede asignar un valor inicial a un nuevo DateTime valor de muchas maneras diferentes:You can assign an initial value to a new DateTime value in many different ways:
- Llamar a un constructor, ya sea cuando se especifican argumentos para valores, o se usa el constructor sin parámetros implícito.Calling a constructor, either one where you specify arguments for values, or use the implicit parameterless constructor.
- Asignar un
DateTimeal valor devuelto de una propiedad o método.Assigning aDateTimeto the return value of a property or method. - Analizar un
DateTimevalor a partir de su representación de cadena.Parsing aDateTimevalue from its string representation. - Usar características del lenguaje específico de Visual Basic para crear instancias de un
DateTime.Using Visual Basic-specific language features to instantiate aDateTime.
Los fragmentos de código siguientes muestran ejemplos de cada uno de ellos:The following code snippets show examples of each:
Constructores de invocaciónInvoke Constructors
Se llama a cualquiera de las sobrecargas del DateTime constructor que especifican elementos del valor de fecha y hora (como el año, el mes y el día, o el número de pasos).You call any of the overloads of the DateTime constructor that specify elements of the date and time value (such as the year, month, and day, or the number of ticks). El código siguiente crea una fecha específica mediante el DateTime constructor que especifica el año, mes, día, hora, minuto y segundo.The following code creates a specific date using the DateTime constructor specifying the year, month, day, hour, minute, and second.
[!code-vbSystem.DateTime.Instantiation#1][!code-vbSystem.DateTime.Instantiation#1]
var date1 = new DateTime(2008, 5, 1, 8, 30, 52);
Console.WriteLine(date1);
Se invoca el DateTime constructor sin parámetros implícito de la estructura cuando se desea DateTime inicializar en su valor predeterminado.You invoke the DateTime structure's implicit parameterless constructor when you want a DateTime initialized to its default value. (Para obtener información detallada sobre el constructor sin parámetros implícito de un tipo de valor, vea tipos de valor). Algunos compiladores también admiten la declaración de un DateTime valor sin asignarle explícitamente un valor.(For details on the implicit parameterless constructor of a value type, see Value Types.) Some compilers also support declaring a DateTime value without explicitly assigning a value to it. La creación de un valor sin una inicialización explícita también da como resultado el valor predeterminado.Creating a value without an explicit initialization also results in the default value. En el ejemplo siguiente se muestra el DateTime constructor sin parámetros implícito en C# y Visual Basic, así como una DateTime declaración sin asignación en Visual Basic.The following example illustrates the DateTime implicit parameterless constructor in C# and Visual Basic, as well as a DateTime declaration without assignment in Visual Basic.
Dim dat1 As DateTime
' The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture))
' The following method call displays True.
Console.WriteLine(dat1.Equals(Date.MinValue))
Dim dat2 As New DateTime()
' The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat2.ToString(System.Globalization.CultureInfo.InvariantCulture))
' The following method call displays True.
Console.WriteLine(dat2.Equals(Date.MinValue))
var dat1 = new DateTime();
// The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
// The following method call displays True.
Console.WriteLine(dat1.Equals(DateTime.MinValue));
Asignación de un valor calculadoAssigning a computed value
Puede asignar el DateTime objeto a un valor de fecha y hora devuelto por una propiedad o un método.You can assign the DateTime object a date and time value returned by a property or method. En el ejemplo siguiente se asigna la fecha y hora actuales, la fecha y hora de la hora universal coordinada (UTC) y la fecha actual a tres nuevas DateTime variables.The following example assigns the current date and time, the current Coordinated Universal Time (UTC) date and time, and the current date to three new DateTime variables.
[!code-vbSystem.DateTime.Instantiation#3][!code-vbSystem.DateTime.Instantiation#3]
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.UtcNow;
DateTime date3 = DateTime.Today;
Analizar una cadena que representa un valor de fecha y horaParsing a string that represents a DateTime
Los Parse ParseExact métodos,, TryParse y TryParseExact convierten una cadena en su valor de fecha y hora equivalente.The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. En los ejemplos siguientes se usan los Parse ParseExact métodos y para analizar una cadena y convertirla en un DateTime valor.The following examples use the Parse and ParseExact methods to parse a string and convert it to a DateTime value. El segundo formato utiliza un formulario admitido por el estándar ISO 8601 para un que representa una fecha y hora en formato de cadena.The second format uses a form supported by the ISO 8601 standard for a representing date and time in string format. Esta representación estándar se usa a menudo para transferir información de fecha en servicios Web.This standard representation is often used to transfer date information in web services.
[!code-vbSystem.DateTime.Instantiation#4][!code-vbSystem.DateTime.Instantiation#4]
var dateString = "5/1/2008 8:30:52 AM";
DateTime date1 = DateTime.Parse(dateString,
System.Globalization.CultureInfo.InvariantCulture);
var iso8601String = "20080501T08:30:52Z";
DateTime dateISO8602 = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ",
System.Globalization.CultureInfo.InvariantCulture);
Los TryParse TryParseExact métodos y indican si una cadena es una representación válida de un DateTime valor y, si es así, realiza la conversión.The TryParse and TryParseExact methods indicate whether a string is a valid representation of a DateTime value and, if it is, performs the conversion.
Sintaxis específica del lenguaje para Visual BasicLanguage-specific syntax for Visual Basic
La siguiente instrucción Visual Basic Inicializa un nuevo DateTime valor.The following Visual Basic statement initializes a new DateTime value.
[!code-vbSystem.DateTime.Instantiation#2][!code-vbSystem.DateTime.Instantiation#2]
Valores DateTime y sus representaciones de cadenaDateTime values and their string representations
Internamente, todos los DateTime valores se representan como el número de TICs (el número de intervalos de 100 segundos) que han transcurrido desde la 12:00:00 de la medianoche del 1 de enero de 0001.Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. El DateTime valor real es independiente del modo en que aparece ese valor cuando se muestra.The actual DateTime value is independent of the way in which that value appears when displayed. La apariencia de un DateTime valor es el resultado de una operación de formato que convierte un valor en su representación de cadena.The appearance of a DateTime value is the result of a formatting operation that converts a value to its string representation.
La apariencia de los valores de fecha y hora depende de la referencia cultural, estándares internacionales, requisitos de la aplicación y preferencias personales.The appearance of date and time values is dependent on culture, international standards, application requirements, and personal preference. La DateTime estructura ofrece flexibilidad para dar formato a los valores de fecha y hora a través de las sobrecargas de ToString .The DateTime structure offers flexibility in formatting date and time values through overloads of ToString. El DateTime.ToString() método predeterminado devuelve la representación de cadena de un valor de fecha y hora usando el patrón de fecha corta y hora larga de la referencia cultural actual.The default DateTime.ToString() method returns the string representation of a date and time value using the current culture's short date and long time pattern. En el ejemplo siguiente se usa el DateTime.ToString() método predeterminado.The following example uses the default DateTime.ToString() method. Muestra la fecha y la hora con el patrón de fecha corta y hora larga de la referencia cultural actual.It displays the date and time using the short date and long time pattern for the current culture. La referencia cultural en-US es la referencia cultural actual en el equipo en el que se ejecutó el ejemplo.The en-US culture is the current culture on the computer on which the example was run.
[!code-csharpSystem.DateTime.Formatting#1][!code-csharpSystem.DateTime.Formatting#1]
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString())
' For en-US culture, displays 3/1/2008 7:00:00 AM
Es posible que deba dar formato a las fechas de una referencia cultural específica para admitir escenarios Web en los que el servidor puede estar en una referencia cultural diferente del cliente.You may need to format dates in a specific culture to support web scenarios where the server may be in a different culture from the client. La referencia cultural se especifica mediante el DateTime.ToString(IFormatProvider) método para crear la representación de fecha corta y hora larga en una referencia cultural concreta.You specify the culture using the DateTime.ToString(IFormatProvider) method to create the short date and long time representation in a specific culture. En el ejemplo siguiente se usa el DateTime.ToString(IFormatProvider) método para mostrar la fecha y la hora utilizando el patrón de fecha corta y hora larga para la referencia cultural fr-fr.The following example uses the DateTime.ToString(IFormatProvider) method to display the date and time using the short date and long time pattern for the fr-FR culture.
var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 01/03/2008 07:00:00
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 01/03/2008 07:00:00
Otras aplicaciones pueden requerir distintas representaciones de cadena de una fecha.Other applications may require different string representations of a date. El DateTime.ToString(String) método devuelve la representación de cadena definida por un especificador de formato estándar o personalizado usando las convenciones de formato de la referencia cultural actual.The DateTime.ToString(String) method returns the string representation defined by a standard or custom format specifier using the formatting conventions of the current culture. En el ejemplo siguiente se usa el DateTime.ToString(String) método para mostrar el patrón de fecha y hora completo de la referencia cultural en-US, la referencia cultural actual en el equipo en el que se ejecutó el ejemplo.The following example uses the DateTime.ToString(String) method to display the full date and time pattern for the en-US culture, the current culture on the computer on which the example was run.
[!code-csharpSystem.DateTime.Formatting#3][!code-csharpSystem.DateTime.Formatting#3]
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("F"))
' Displays Saturday, March 01, 2008 7:00:00 AM
Por último, puede especificar la referencia cultural y el formato mediante el DateTime.ToString(String, IFormatProvider) método.Finally, you can specify both the culture and the format using the DateTime.ToString(String, IFormatProvider) method. En el ejemplo siguiente se usa el DateTime.ToString(String, IFormatProvider) método para mostrar el patrón de fecha y hora completo de la referencia cultural fr-fr.The following example uses the DateTime.ToString(String, IFormatProvider) method to display the full date and time pattern for the fr-FR culture.
var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F", new System.Globalization.CultureInfo("fr-FR")));
// Displays samedi 1 mars 2008 07:00:00
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("F", New System.Globalization.CultureInfo("fr-FR")))
' Displays samedi 1 mars 2008 07:00:00
La DateTime.ToString(String) sobrecarga también se puede utilizar con una cadena de formato personalizado para especificar otros formatos.The DateTime.ToString(String) overload can also be used with a custom format string to specify other formats. En el ejemplo siguiente se muestra cómo dar formato a una cadena con el formato estándar ISO 8601 , que a menudo se usa para los servicios Web.The following example shows how to format a string using the ISO 8601 standard format often used for web services. El formato ISO 8601 no tiene una cadena de formato estándar correspondiente.The Iso 8601 format does not have a corresponding standard format string.
var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("yyyyMMddTHH:mm:ssZ"));
// Displays 20080301T07:00:00Z
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("yyyyMMddTHH:mm:ssZ"))
' Displays 20080301T07:00:00Z
Para obtener más información sobre DateTime los valores de formato, vea cadenas con formato de fecha y hora estándar y cadenas con formato de fecha y hora personalizado.For more information about formatting DateTime values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Analizar valores DateTime de cadenasParsing DateTime values from strings
El análisis convierte la representación de cadena de una fecha y hora en un DateTime valor.Parsing converts the string representation of a date and time to a DateTime value. Normalmente, las cadenas de fecha y hora tienen dos usos diferentes en las aplicaciones:Typically, date and time strings have two different usages in applications:
Una fecha y hora toma una gran variedad de formas y refleja las convenciones de la referencia cultural actual o de una referencia cultural concreta.A date and time takes a variety of forms and reflects the conventions of either the current culture or a specific culture. Por ejemplo, una aplicación permite a un usuario cuya referencia cultural actual es en-US introducir un valor de fecha como "12/15/2013" o "15 de diciembre de 2013".For example, an application allows a user whose current culture is en-US to input a date value as "12/15/2013" or "December 15, 2013". Permite que un usuario cuya referencia cultural actual sea en-GB para que escriba un valor de fecha como "15/12/2013" o "15 de diciembre de 2013".It allows a user whose current culture is en-gb to input a date value as "15/12/2013" or "15 December 2013."
Una fecha y hora se representan en un formato predefinido.A date and time is represented in a predefined format. Por ejemplo, una aplicación serializa una fecha como "20130103" independientemente de la referencia cultural en la que se ejecuta la aplicación.For example, an application serializes a date as "20130103" independently of the culture on which the app is running. Una aplicación puede requerir que se especifiquen fechas en el formato de fecha corta de la referencia cultural actual.An application may require dates be input in the current culture's short date format.
Use el Parse método o TryParse para convertir una cadena de uno de los formatos de fecha y hora comunes utilizados por una referencia cultural a un DateTime valor.You use the Parse or TryParse method to convert a string from one of the common date and time formats used by a culture to a DateTime value. En el ejemplo siguiente se muestra cómo se puede usar TryParse para convertir cadenas de fecha en diferentes formatos específicos de la referencia cultural en un DateTime valor.The following example shows how you can use TryParse to convert date strings in different culture-specific formats to a DateTime value. Cambia la referencia cultural actual a Inglés (Gran Bretaña) y llama al GetDateTimeFormats() método para generar una matriz de cadenas de fecha y hora.It changes the current culture to English (Great Britain) and calls the GetDateTimeFormats() method to generate an array of date and time strings. A continuación, pasa cada elemento de la matriz al TryParse método.It then passes each element in the array to the TryParse method. La salida del ejemplo muestra que el método de análisis pudo convertir correctamente cada una de las cadenas de fecha y hora específicas de la referencia cultural.The output from the example shows the parsing method was able to successfully convert each of the culture-specific date and time strings.
System.Threading.Thread.CurrentThread.CurrentCulture =
System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
var date1 = new DateTime(2013, 6, 1, 12, 32, 30);
var badFormats = new List<String>();
Console.WriteLine($"{"Date String",-37} {"Date",-19}\n");
foreach (var dateString in date1.GetDateTimeFormats())
{
DateTime parsedDate;
if (DateTime.TryParse(dateString, out parsedDate))
Console.WriteLine($"{dateString,-37} {DateTime.Parse(dateString),-19}");
else
badFormats.Add(dateString);
}
// Display strings that could not be parsed.
if (badFormats.Count > 0)
{
Console.WriteLine("\nStrings that could not be parsed: ");
foreach (var badFormat in badFormats)
Console.WriteLine($" {badFormat}");
}
// Press "Run" to see the output.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
Dim date1 As New DateTime(2013, 6, 1, 12, 32, 30)
Dim badFormats As New List(Of String)
Console.WriteLine($"{"Date String",-37} {"Date",-19}")
Console.WriteLine()
For Each dateString As String In date1.GetDateTimeFormats()
Dim parsedDate As DateTime
If DateTime.TryParse(dateString, parsedDate) Then
Console.WriteLine($"{dateString,-37} {DateTime.Parse(dateString),-19:g}")
Else
badFormats.Add(dateString)
End If
Next
' Display strings that could not be parsed.
If badFormats.Count > 0 Then
Console.WriteLine()
Console.WriteLine("Strings that could not be parsed: ")
For Each badFormat In badFormats
Console.WriteLine($" {badFormat}")
Next
End If
' The example displays the following output:
' Date String Date
'
' 01/06/2013 01/06/2013 00:00:00
' 01/06/13 01/06/2013 00:00:00
' 1/6/13 01/06/2013 00:00:00
' 1.6.13 01/06/2013 00:00:00
' 2013-06-01 01/06/2013 00:00:00
' 01 June 2013 01/06/2013 00:00:00
' 1 June 2013 01/06/2013 00:00:00
' 01 June 2013 12:32 01/06/2013 12:32:00
' 01 June 2013 12:32 01/06/2013 12:32:00
' 01 June 2013 12:32 PM 01/06/2013 12:32:00
' 01 June 2013 12:32 PM 01/06/2013 12:32:00
' 1 June 2013 12:32 01/06/2013 12:32:00
' 1 June 2013 12:32 01/06/2013 12:32:00
' 1 June 2013 12:32 PM 01/06/2013 12:32:00
' 1 June 2013 12:32 PM 01/06/2013 12:32:00
' 01 June 2013 12:32:30 01/06/2013 12:32:30
' 01 June 2013 12:32:30 01/06/2013 12:32:30
' 01 June 2013 12:32:30 PM 01/06/2013 12:32:30
' 01 June 2013 12:32:30 PM 01/06/2013 12:32:30
' 1 June 2013 12:32:30 01/06/2013 12:32:30
' 1 June 2013 12:32:30 01/06/2013 12:32:30
' 1 June 2013 12:32:30 PM 01/06/2013 12:32:30
' 1 June 2013 12:32:30 PM 01/06/2013 12:32:30
' 01/06/2013 12:32 01/06/2013 12:32:00
' 01/06/2013 12:32 01/06/2013 12:32:00
' 01/06/2013 12:32 PM 01/06/2013 12:32:00
' 01/06/2013 12:32 PM 01/06/2013 12:32:00
' 01/06/13 12:32 01/06/2013 12:32:00
' 01/06/13 12:32 01/06/2013 12:32:00
' 01/06/13 12:32 PM 01/06/2013 12:32:00
' 01/06/13 12:32 PM 01/06/2013 12:32:00
' 1/6/13 12:32 01/06/2013 12:32:00
' 1/6/13 12:32 01/06/2013 12:32:00
' 1/6/13 12:32 PM 01/06/2013 12:32:00
' 1/6/13 12:32 PM 01/06/2013 12:32:00
' 1.6.13 12:32 01/06/2013 12:32:00
' 1.6.13 12:32 01/06/2013 12:32:00
' 1.6.13 12:32 PM 01/06/2013 12:32:00
' 1.6.13 12:32 PM 01/06/2013 12:32:00
' 2013-06-01 12:32 01/06/2013 12:32:00
' 2013-06-01 12:32 01/06/2013 12:32:00
' 2013-06-01 12:32 PM 01/06/2013 12:32:00
' 2013-06-01 12:32 PM 01/06/2013 12:32:00
' 01/06/2013 12:32:30 01/06/2013 12:32:30
' 01/06/2013 12:32:30 01/06/2013 12:32:30
' 01/06/2013 12:32:30 PM 01/06/2013 12:32:30
' 01/06/2013 12:32:30 PM 01/06/2013 12:32:30
' 01/06/13 12:32:30 01/06/2013 12:32:30
' 01/06/13 12:32:30 01/06/2013 12:32:30
' 01/06/13 12:32:30 PM 01/06/2013 12:32:30
' 01/06/13 12:32:30 PM 01/06/2013 12:32:30
' 1/6/13 12:32:30 01/06/2013 12:32:30
' 1/6/13 12:32:30 01/06/2013 12:32:30
' 1/6/13 12:32:30 PM 01/06/2013 12:32:30
' 1/6/13 12:32:30 PM 01/06/2013 12:32:30
' 1.6.13 12:32:30 01/06/2013 12:32:30
' 1.6.13 12:32:30 01/06/2013 12:32:30
' 1.6.13 12:32:30 PM 01/06/2013 12:32:30
' 1.6.13 12:32:30 PM 01/06/2013 12:32:30
' 2013-06-01 12:32:30 01/06/2013 12:32:30
' 2013-06-01 12:32:30 01/06/2013 12:32:30
' 2013-06-01 12:32:30 PM 01/06/2013 12:32:30
' 2013-06-01 12:32:30 PM 01/06/2013 12:32:30
' 01 June 01/06/2013 00:00:00
' 01 June 01/06/2013 00:00:00
' 2013-06-01T12:32:30.0000000 01/06/2013 12:32:30
' 2013-06-01T12:32:30.0000000 01/06/2013 12:32:30
' Sat, 01 Jun 2013 12:32:30 GMT 01/06/2013 05:32:30
' Sat, 01 Jun 2013 12:32:30 GMT 01/06/2013 05:32:30
' 2013-06-01T12:32:30 01/06/2013 12:32:30
' 12:32 22/04/2013 12:32:00
' 12:32 22/04/2013 12:32:00
' 12:32 PM 22/04/2013 12:32:00
' 12:32 PM 22/04/2013 12:32:00
' 12:32:30 22/04/2013 12:32:30
' 12:32:30 22/04/2013 12:32:30
' 12:32:30 PM 22/04/2013 12:32:30
' 12:32:30 PM 22/04/2013 12:32:30
' 2013-06-01 12:32:30Z 01/06/2013 05:32:30
' 01 June 2013 19:32:30 01/06/2013 19:32:30
' 01 June 2013 19:32:30 01/06/2013 19:32:30
' 01 June 2013 07:32:30 PM 01/06/2013 19:32:30
' 01 June 2013 7:32:30 PM 01/06/2013 19:32:30
' 1 June 2013 19:32:30 01/06/2013 19:32:30
' 1 June 2013 19:32:30 01/06/2013 19:32:30
' 1 June 2013 07:32:30 PM 01/06/2013 19:32:30
' 1 June 2013 7:32:30 PM 01/06/2013 19:32:30
' June 2013 01/06/2013 00:00:00
' June 2013 01/06/2013 00:00:00
Los ParseExact métodos y se usan TryParseExact para convertir una cadena que debe coincidir con un formato o formatos determinados en un DateTime valor.You use the ParseExact and TryParseExact methods to convert a string that must match a particular format or formats to a DateTime value. Especifique una o más cadenas de formato de fecha y hora como parámetro para el método de análisis.You specify one or more date and time format strings as a parameter to the parsing method. En el ejemplo siguiente se usa el TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) método para convertir cadenas que deben tener un formato "AAAAMMDD" o un formato "HHMMSS" con DateTime valores.The following example uses the TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to DateTime values.
[!code-csharpSystem.DateTime.Parsing#2][!code-csharpSystem.DateTime.Parsing#2]
Dim formats() As String = {"yyyyMMdd", "HHmmss"}
Dim dateStrings() As String = {"20130816", "20131608",
" 20130816 ", "115216",
"521116", " 115216 "}
Dim parsedDate As DateTime
For Each dateString As String In dateStrings
If DateTime.TryParseExact(dateString, formats, Nothing,
DateTimeStyles.AllowWhiteSpaces Or
DateTimeStyles.AdjustToUniversal,
parsedDate) Then
Console.WriteLine($"{dateString} --> {parsedDate:g}")
Else
Console.WriteLine($"Cannot convert {dateString}")
End If
Next
' The example displays the following output:
' 20130816 --> 8/16/2013 12:00 AM
' Cannot convert 20131608
' 20130816 --> 8/16/2013 12:00 AM
' 115216 --> 4/22/2013 11:52 AM
' Cannot convert 521116
' 115216 --> 4/22/2013 11:52 AM
Un uso común de ParseExact consiste en convertir una representación de cadena de un servicio Web, normalmente en formato estándar ISO 8601 .One common use for ParseExact is to convert a string representation from a web service, usually in ISO 8601 standard format. En el código siguiente se muestra la cadena de formato correcta que se debe usar:The following code shows the correct format string to use:
var iso8601String = "20080501T08:30:52Z";
DateTime dateISO8602 = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ",
System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine($"{iso8601String} --> {dateISO8602:g}");
Dim iso8601String As String = "20080501T08:30:52Z"
Dim dateISO8602 As DateTime = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)
Console.WriteLine($"{iso8601String} --> {dateISO8602:g}")
Si no se puede analizar una cadena, los Parse ParseExact métodos y producen una excepción.If a string cannot be parsed, the Parse and ParseExact methods throw an exception. Los TryParse TryParseExact métodos y devuelven un Boolean valor que indica si la conversión se realizó correctamente o no.The TryParse and TryParseExact methods return a Boolean value that indicates whether the conversion succeeded or failed. Debe usar los TryParse métodos o TryParseExact en escenarios donde el rendimiento es importante.You should use the TryParse or TryParseExact methods in scenarios where performance is important. La operación de análisis de las cadenas de fecha y hora tiende a tener una alta tasa de errores y el control de excepciones es caro.The parsing operation for date and time strings tends to have a high failure rate, and exception handling is expensive. Utilice estos métodos si las cadenas son entradas por los usuarios o proceden de un origen desconocido.Use these methods if strings are input by users or coming from an unknown source.
Para obtener más información sobre cómo analizar valores de fecha y hora, vea analizar cadenas de fecha y hora.For more information about parsing date and time values, see Parsing Date and Time Strings.
Valores DateTimeDateTime values
Las descripciones de los valores de hora del DateTime tipo suelen expresarse con el estándar de hora universal coordinada (UTC).Descriptions of time values in the DateTime type are often expressed using the Coordinated Universal Time (UTC) standard. La hora universal coordinada es el nombre reconocido internacionalmente para la hora del meridiano de Greenwich (GMT).Coordinated Universal Time is the internationally recognized name for Greenwich Mean Time (GMT). La hora universal coordinada es el tiempo medido con una longitud de cero grados, el punto de origen de la hora UTC.Coordinated Universal Time is the time as measured at zero degrees longitude, the UTC origin point. El horario de verano no es aplicable a la hora UTC.Daylight saving time is not applicable to UTC.
La hora local es relativa a una zona horaria determinada.Local time is relative to a particular time zone. Una zona horaria está asociada a un ajuste de zona horaria.A time zone is associated with a time zone offset. Un ajuste de zona horaria es el desplazamiento de la zona horaria medido en horas desde el punto de origen de la hora UTC.A time zone offset is the displacement of the time zone measured in hours from the UTC origin point. Además, la hora local se ve afectada opcionalmente por el horario de verano, que agrega o resta un ajuste de intervalo de tiempo.In addition, local time is optionally affected by daylight saving time, which adds or subtracts a time interval adjustment. La hora local se calcula agregando el ajuste de zona horaria a la hora UTC y ajustando el horario de verano si es necesario.Local time is calculated by adding the time zone offset to UTC and adjusting for daylight saving time if necessary. El ajuste de zona horaria en el punto de origen de UTC es cero.The time zone offset at the UTC origin point is zero.
La hora UTC es adecuada para los cálculos, las comparaciones y el almacenamiento de fechas y horas en archivos.UTC time is suitable for calculations, comparisons, and storing dates and time in files. La hora local es adecuada para mostrarse en las interfaces de usuario de las aplicaciones de escritorio.Local time is appropriate for display in user interfaces of desktop applications. Las aplicaciones que tienen en cuenta la zona horaria (por ejemplo, muchas aplicaciones web) también necesitan trabajar con varias zonas horarias.Time zone-aware applications (such as many Web applications) also need to work with a number of other time zones.
Si la Kind propiedad de un DateTime objeto es DateTimeKind.Unspecified , no se especifica si la hora representada es la hora local, la hora UTC o una hora en alguna otra zona horaria.If the Kind property of a DateTime object is DateTimeKind.Unspecified, it is unspecified whether the time represented is local time, UTC time, or a time in some other time zone.
Resolución de DateTimeDateTime resolution
Nota
Como alternativa a realizar operaciones aritméticas de fecha y hora en DateTime valores para medir el tiempo transcurrido, puede utilizar la Stopwatch clase.As an alternative to performing date and time arithmetic on DateTime values to measure elapsed time, you can use the Stopwatch class.
La Ticks propiedad expresa los valores de fecha y hora en unidades de 1 10-millonésimas de segundo.The Ticks property expresses date and time values in units of one ten-millionth of a second. La Millisecond propiedad devuelve las milésimas de segundo de un valor de fecha y hora.The Millisecond property returns the thousandths of a second in a date and time value. El uso de llamadas repetidas a la DateTime.Now propiedad para medir el tiempo transcurrido depende del reloj del sistema.Using repeated calls to the DateTime.Now property to measure elapsed time is dependent on the system clock. El reloj del sistema en los sistemas Windows 7 y Windows 8 tiene una resolución de aproximadamente 15 milisegundos.The system clock on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds. Esta resolución afecta a intervalos de tiempo pequeños inferiores a 100 milisegundos.This resolution affects small time intervals less than 100 milliseconds.
En el ejemplo siguiente se muestra la dependencia de los valores de fecha y hora actuales en la resolución del reloj del sistema.The following example illustrates the dependence of current date and time values on the resolution of the system clock. En el ejemplo, un bucle externo se repite 20 veces y un bucle interno sirve para retrasar el bucle externo.In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. Si el valor del contador de bucle exterior es 10, una llamada al Thread.Sleep método presenta un retraso de cinco milisegundos.If the value of the outer loop counter is 10, a call to the Thread.Sleep method introduces a five-millisecond delay. En el ejemplo siguiente se muestra el número de milisegundos devueltos por los DateTime.Now.Milliseconds cambios de propiedad solo después de la llamada a Thread.Sleep .The following example shows the number of milliseconds returned by the DateTime.Now.Milliseconds property changes only after the call to Thread.Sleep.
string output = "";
for (int ctr = 0; ctr <= 20; ctr++)
{
output += String.Format($"{DateTime.Now.Millisecond}\n");
// Introduce a delay loop.
for (int delay = 0; delay <= 1000; delay++)
{ }
if (ctr == 10)
{
output += "Thread.Sleep called...\n";
System.Threading.Thread.Sleep(5);
}
}
Console.WriteLine(output);
// Press "Run" to see the output.
Dim output As String = ""
For ctr As Integer = 0 To 20
output += Date.Now.Millisecond.ToString() + vbCrLf
' Introduce a delay loop.
For delay As Integer = 0 To 1000
Next
If ctr = 10 Then
output += "Thread.Sleep called..." + vbCrLf
Thread.Sleep(5)
End If
Next
Console.WriteLine(output)
' The example displays output like the following:
' 111
' 111
' 111
' 111
' 111
' 111
' 111
' 111
' 111
' 111
' 111
' Thread.Sleep called...
' 143
' 143
' 143
' 143
' 143
' 143
' 143
' 143
' 143
' 143
Operaciones DateTimeDateTime operations
Un cálculo que usa una DateTime estructura, como Add o Subtract , no modifica el valor de la estructura.A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. En su lugar, el cálculo devuelve una nueva DateTime estructura cuyo valor es el resultado del cálculo.Instead, the calculation returns a new DateTime structure whose value is the result of the calculation.
Las operaciones de conversión entre zonas horarias (por ejemplo, entre la hora UTC y la hora local, o entre una zona horaria y otra) tienen en cuenta el horario de verano, pero las operaciones aritméticas y de comparación no lo hacen.Conversion operations between time zones (such as between UTC and local time, or between one time zone and another) take daylight saving time into account, but arithmetic and comparison operations do not.
La DateTime propia estructura ofrece compatibilidad limitada para convertir de una zona horaria a otra.The DateTime structure itself offers limited support for converting from one time zone to another. Puede usar el ToLocalTime método para convertir la hora UTC a la hora local, o puede usar el ToUniversalTime método para convertir de la hora local a la hora UTC.You can use the ToLocalTime method to convert UTC to local time, or you can use the ToUniversalTime method to convert from local time to UTC. Sin embargo, hay disponible un conjunto completo de métodos de conversión de zona horaria en la TimeZoneInfo clase.However, a full set of time zone conversion methods is available in the TimeZoneInfo class. Puede convertir la hora en cualquiera de las zonas horarias del mundo a la hora de cualquier otra zona horaria mediante estos métodos.You convert the time in any one of the world's time zones to the time in any other time zone using these methods.
Los cálculos y las comparaciones de DateTime objetos solo son significativos si los objetos representan horas en la misma zona horaria.Calculations and comparisons of DateTime objects are meaningful only if the objects represent times in the same time zone. Puede usar un TimeZoneInfo objeto para representar DateTime la zona horaria de un valor, aunque los dos están acoplados de forma flexible.You can use a TimeZoneInfo object to represent a DateTime value's time zone, although the two are loosely coupled. Un DateTime objeto no tiene una propiedad que devuelve un objeto que representa la zona horaria de ese valor de fecha y hora.A DateTime object does not have a property that returns an object that represents that date and time value's time zone. La Kind propiedad indica si un DateTime representa una hora UTC, una hora local o no se ha especificado.The Kind property indicates if a DateTime represents UTC, local time, or is unspecified. En una aplicación que tenga en cuenta la zona horaria, debe basarse en algún mecanismo externo para determinar la zona horaria en la que DateTime se creó un objeto.In a time zone-aware application, you must rely on some external mechanism to determine the time zone in which a DateTime object was created. Puede usar una estructura que incluya tanto el DateTime valor como el TimeZoneInfo objeto que representa la DateTime zona horaria del valor.You could use a structure that wraps both the DateTime value and the TimeZoneInfo object that represents the DateTime value's time zone. Para obtener información detallada sobre el uso de UTC en cálculos y comparaciones con DateTime valores, vea realizar operaciones aritméticas con fechas y horas.For details on using UTC in calculations and comparisons with DateTime values, see Performing Arithmetic Operations with Dates and Times.
Cada DateTime miembro usa implícitamente el calendario gregoriano para realizar su operación.Each DateTime member implicitly uses the Gregorian calendar to perform its operation. Las excepciones son métodos que especifican implícitamente un calendario.Exceptions are methods that implicitly specify a calendar. Estos incluyen constructores que especifican un calendario y métodos con un parámetro derivado de IFormatProvider , como System.Globalization.DateTimeFormatInfo .These include constructors that specify a calendar, and methods with a parameter derived from IFormatProvider, such as System.Globalization.DateTimeFormatInfo.
Las operaciones de los miembros del DateTime tipo tienen en cuenta los detalles, como los años bisiestos y el número de días de un mes.Operations by members of the DateTime type take into account details such as leap years and the number of days in a month.
Valores de DateTime y calendariosDateTime values and calendars
La biblioteca de clases de .NET Framework incluye varias clases de calendario, que se derivan de la Calendar clase.The .NET Framework Class Library includes a number of calendar classes, all of which are derived from the Calendar class. Son las siguientes:They are:
- La clase ChineseLunisolarCalendar.The ChineseLunisolarCalendar class.
- La clase EastAsianLunisolarCalendar.The EastAsianLunisolarCalendar class.
- La clase GregorianCalendar.The GregorianCalendar class.
- La clase HebrewCalendar.The HebrewCalendar class.
- La clase HijriCalendar.The HijriCalendar class.
- La clase JapaneseCalendar.The JapaneseCalendar class.
- La clase JapaneseLunisolarCalendar.The JapaneseLunisolarCalendar class.
- La clase JulianCalendar.The JulianCalendar class.
- La clase KoreanCalendar.The KoreanCalendar class.
- La clase KoreanLunisolarCalendar.The KoreanLunisolarCalendar class.
- La clase PersianCalendar.The PersianCalendar class.
- La clase TaiwanCalendar.The TaiwanCalendar class.
- La clase TaiwanLunisolarCalendar.The TaiwanLunisolarCalendar class.
- La clase ThaiBuddhistCalendar.The ThaiBuddhistCalendar class.
- La clase UmAlQuraCalendar.The UmAlQuraCalendar class.
Importante
Las eras en los calendarios japoneses se basan en el reino del emperador y, por tanto, se espera que cambien.Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. Por ejemplo, el 1 de mayo de 2019 marcaba el comienzo de la era Reiwa en JapaneseCalendar y JapaneseLunisolarCalendar.For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. Este cambio de era afecta a todas las aplicaciones que usan estos calendarios.Such a change of era affects all applications that use these calendars. Para obtener más información y determinar si sus aplicaciones están entre las afectadas, consulte Handling a new era in the Japanese calendar in .NET (Gestión de una nueva era del calendario japonés en .NET).See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. Para obtener más información sobre cómo probar aplicaciones en sistemas Windows para garantizar que estén preparadas para el cambio de era, consulte Prepare your application for the Japanese era change (Preparación de la aplicación para el cambio de era japonesa).See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. Consulte Trabajar con eras para ver las características de .NET que admiten calendarios con varias eras y procedimientos recomendados al trabajar con calendarios que admiten varias eras.See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.
Cada referencia cultural utiliza un calendario predeterminado definido por su propiedad de solo lectura CultureInfo.Calendar .Each culture uses a default calendar defined by its read-only CultureInfo.Calendar property. Cada referencia cultural puede admitir uno o varios calendarios definidos por su propiedad de solo lectura CultureInfo.OptionalCalendars .Each culture may support one or more calendars defined by its read-only CultureInfo.OptionalCalendars property. El calendario que usa actualmente un CultureInfo objeto específico se define mediante su DateTimeFormatInfo.Calendar propiedad.The calendar currently used by a specific CultureInfo object is defined by its DateTimeFormatInfo.Calendar property. Debe ser uno de los calendarios que se encuentran en la CultureInfo.OptionalCalendars matriz.It must be one of the calendars found in the CultureInfo.OptionalCalendars array.
El calendario actual de una referencia cultural se usa en todas las operaciones de formato de esa referencia cultural.A culture's current calendar is used in all formatting operations for that culture. Por ejemplo, el calendario predeterminado de la referencia cultural budista tailandés es el calendario de la era budista tailandés, que se representa mediante la ThaiBuddhistCalendar clase.For example, the default calendar of the Thai Buddhist culture is the Thai Buddhist Era calendar, which is represented by the ThaiBuddhistCalendar class. Cuando CultureInfo se usa un objeto que representa la referencia cultural budista tailandesa en una operación de formato de fecha y hora, se usa de forma predeterminada el calendario de la era budista tailandés.When a CultureInfo object that represents the Thai Buddhist culture is used in a date and time formatting operation, the Thai Buddhist Era calendar is used by default. El calendario gregoriano solo se utiliza si se cambia la propiedad de la referencia cultural DateTimeFormatInfo.Calendar , como se muestra en el ejemplo siguiente:The Gregorian calendar is used only if the culture's DateTimeFormatInfo.Calendar property is changed, as the following example shows:
[!code-csharpSystem.DateTime.Calendar#1][!code-csharpSystem.DateTime.Calendar#1]
Dim thTH As New CultureInfo("th-TH")
Dim value As New DateTime(2016, 5, 28)
Console.WriteLine(value.ToString(thTH))
thTH.DateTimeFormat.Calendar = New GregorianCalendar()
Console.WriteLine(value.ToString(thTH))
' The example displays the following output:
' 28/5/2559 0:00:00
' 28/5/2016 0:00:00
El calendario actual de una referencia cultural también se usa en todas las operaciones de análisis de esa referencia cultural, como se muestra en el ejemplo siguiente.A culture's current calendar is also used in all parsing operations for that culture, as the following example shows.
[!code-csharpSystem.DateTime.Calendar#2][!code-csharpSystem.DateTime.Calendar#2]
Private Sub ThaiBuddhistEraParse()
Dim thTH As New CultureInfo("th-TH")
Dim value As DateTime = DateTime.Parse("28/5/2559", thTH)
Console.WriteLine(value.ToString(thTH))
thTH.DateTimeFormat.Calendar = New GregorianCalendar()
Console.WriteLine(value.ToString(thTH))
' The example displays the following output:
' 28/5/2559 0:00:00
' 28/5/2016 0:00:00
End Sub
Las instancias de un DateTime valor se crean mediante los elementos de fecha y hora (número del año, mes y día) de un calendario concreto llamando a un constructor DateTime que incluye un calendar parámetro y pasándole un Calendar objeto que representa ese calendario.You instantiate a DateTime value using the date and time elements (number of the year, month, and day) of a specific calendar by calling a DateTime constructor that includes a calendar parameter and passing it a Calendar object that represents that calendar. En el ejemplo siguiente se usan los elementos de fecha y hora del ThaiBuddhistCalendar calendario.The following example uses the date and time elements from the ThaiBuddhistCalendar calendar.
[!code-csharpSystem.DateTime.Calendar#3][!code-csharpSystem.DateTime.Calendar#3]
Dim thTH As New CultureInfo("th-TH")
Dim dat As New DateTime(2559, 5, 28, thTH.DateTimeFormat.Calendar)
Console.WriteLine($"Thai Buddhist Era date: {dat.ToString("d", thTH)}")
Console.WriteLine($"Gregorian date: {dat:d}")
' The example displays the following output:
' Thai Buddhist Era Date: 28/5/2559
' Gregorian Date: 28/05/2016
DateTime los constructores que no incluyen un calendar parámetro suponen que los elementos de fecha y hora se expresan como unidades en el calendario gregoriano.DateTime constructors that do not include a calendar parameter assume that the date and time elements are expressed as units in the Gregorian calendar.
Todas las demás DateTime propiedades y métodos usan el calendario gregoriano.All other DateTime properties and methods use the Gregorian calendar. Por ejemplo, la DateTime.Year propiedad devuelve el año del calendario gregoriano y el DateTime.IsLeapYear(Int32) método supone que el year parámetro es un año del calendario gregoriano.For example, the DateTime.Year property returns the year in the Gregorian calendar, and the DateTime.IsLeapYear(Int32) method assumes that the year parameter is a year in the Gregorian calendar. Cada DateTime miembro que usa el calendario gregoriano tiene un miembro correspondiente de la Calendar clase que utiliza un calendario específico.Each DateTime member that uses the Gregorian calendar has a corresponding member of the Calendar class that uses a specific calendar. Por ejemplo, el Calendar.GetYear método devuelve el año en un calendario específico y el Calendar.IsLeapYear método interpreta el year parámetro como un número de año en un calendario determinado.For example, the Calendar.GetYear method returns the year in a specific calendar, and the Calendar.IsLeapYear method interprets the year parameter as a year number in a specific calendar. En el ejemplo siguiente se usan tanto DateTime como los miembros correspondientes de la ThaiBuddhistCalendar clase.The following example uses both the DateTime and the corresponding members of the ThaiBuddhistCalendar class.
[!code-csharpSystem.DateTime.Calendar#4][!code-csharpSystem.DateTime.Calendar#4]
Dim thTH As New CultureInfo("th-TH")
Dim cal As Calendar = thTH.DateTimeFormat.Calendar
Dim dat As New DateTime(2559, 5, 28, cal)
Console.WriteLine("Using the Thai Buddhist Era calendar:")
Console.WriteLine($"Date: {dat.ToString("d", thTH)}")
Console.WriteLine($"Year: {cal.GetYear(dat)}")
Console.WriteLine($"Leap year: {cal.IsLeapYear(cal.GetYear(dat))}")
Console.WriteLine()
Console.WriteLine("Using the Gregorian calendar:")
Console.WriteLine($"Date: {dat:d}")
Console.WriteLine($"Year: {dat.Year}")
Console.WriteLine($"Leap year: {DateTime.IsLeapYear(dat.Year)}")
' The example displays the following output:
' Using the Thai Buddhist Era calendar
' Date : 28/5/2559
' Year: 2559
' Leap year : True
'
' Using the Gregorian calendar
' Date : 28/05/2016
' Year: 2016
' Leap year : True
La DateTime estructura incluye una DayOfWeek propiedad que devuelve el día de la semana del calendario gregoriano.The DateTime structure includes a DayOfWeek property that returns the day of the week in the Gregorian calendar. No incluye un miembro que le permita recuperar el número de semana del año.It does not include a member that allows you to retrieve the week number of the year. Para recuperar la semana del año, llame al método del calendario individual Calendar.GetWeekOfYear .To retrieve the week of the year, call the individual calendar's Calendar.GetWeekOfYear method. Esto se muestra en el ejemplo siguiente.The following example provides an illustration.
[!code-csharpSystem.DateTime.Calendar#5][!code-csharpSystem.DateTime.Calendar#5]
Dim thTH As New CultureInfo("th-TH")
Dim thCalendar As Calendar = thTH.DateTimeFormat.Calendar
Dim dat As New DateTime(1395, 8, 18, thCalendar)
Console.WriteLine("Using the Thai Buddhist Era calendar:")
Console.WriteLine($"Date: {dat.ToString("d", thTH)}")
Console.WriteLine($"Day of Week: {thCalendar.GetDayOfWeek(dat)}")
Console.WriteLine($"Week of year: {thCalendar.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, DayOfWeek.Sunday)}")
Console.WriteLine()
Dim greg As Calendar = New GregorianCalendar()
Console.WriteLine("Using the Gregorian calendar:")
Console.WriteLine($"Date: {dat:d}")
Console.WriteLine($"Day of Week: {dat.DayOfWeek}")
Console.WriteLine($"Week of year: {greg.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, DayOfWeek.Sunday)}")
' The example displays the following output:
' Using the Thai Buddhist Era calendar
' Date : 18/8/1395
' Day of Week: Sunday
' Week of year: 34
'
' Using the Gregorian calendar
' Date : 18/08/0852
' Day of Week: Sunday
' Week of year: 34
Para obtener más información sobre las fechas y los calendarios, vea trabajar con calendarios.For more information on dates and calendars, see Working with Calendars.
Conservar valores de fecha y horaPersisting DateTime values
Puede conservar DateTime los valores de cuatro maneras:You can persist DateTime values in four ways:
- Se convierten en cadenas y se conservan las cadenas.You convert them to strings and persist the strings.
- Se convierten en valores enteros de 64 bits (el valor de la Ticks propiedad) y se conservan los enteros.You convert them to 64-bit integer values (the value of the Ticks property) and persist the integers.
- Los valores de fecha y hora se serializan.You serialize the DateTime values.
- Los valores DATETIME se serializan junto con la información de zona horaria.You serialize the DateTime values along with time zone information.
Debe asegurarse de que la rutina que restaura los DateTime valores no pierde datos ni produce una excepción, independientemente de la técnica que elija.You must ensure that the routine that restores the DateTime values doesn't lose data or throw an exception regardless of which technique you choose. DateTime los valores deben ser de ida y vuelta.DateTime values should round-trip. Es decir, el valor original y el valor restaurado deben ser iguales.That is, the original value and the restored value should be the same. Y si el DateTime valor original representa un único instante de tiempo, debe identificar el mismo momento en que se restaura.And if the original DateTime value represents a single instant of time, it should identify the same moment of time when it's restored.
Persistencia de valores como cadenasPersisting values as strings
Para restaurar correctamente DateTime los valores que se conservan como cadenas, siga estas reglas:To successfully restore DateTime values that are persisted as strings, follow these rules:
Haga las mismas suposiciones sobre el formato específico de la referencia cultural al restaurar la cadena como cuando la almacenó.Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. Para asegurarse de que una cadena se puede restaurar en un sistema cuya referencia cultural actual es diferente de la referencia cultural del sistema en que se ha guardado, llame ToString a la sobrecarga para guardar la cadena mediante las convenciones de la referencia cultural de todos los idiomas.To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the ToString overload to save the string by using the conventions of the invariant culture. Llame Parse(String, IFormatProvider, DateTimeStyles) a la TryParse(String, IFormatProvider, DateTimeStyles, DateTime) sobrecarga o para restaurar la cadena mediante las convenciones de la referencia cultural de todos los idiomas.Call the Parse(String, IFormatProvider, DateTimeStyles) or TryParse(String, IFormatProvider, DateTimeStyles, DateTime) overload to restore the string by using the conventions of the invariant culture. Nunca use las ToString() Parse(String) TryParse(String, DateTime) sobrecargas, o, que usan las convenciones de la referencia cultural del subproceso actual.Never use the ToString(), Parse(String), or TryParse(String, DateTime) overloads, which use the conventions of the current thread culture.
Si la fecha representa un único momento, asegúrese de que representa el mismo momento en el tiempo en que se restaura, incluso en una zona horaria diferente.If the date represents a single moment of time, ensure that it represents the same moment in time when it's restored, even on a different time zone. Convierta el DateTime valor en hora universal coordinada (UTC) antes de guardarlo.Convert the DateTime value to Coordinated Universal Time (UTC) before saving it. También puede serializar el valor junto con la información de zona horaria.You can also serialize the value along with time zone information. Para obtener más información sobre este enfoque, vea serializar datos de zona horaria y fecha y hora.For more information about this approach, see Serializing DateTime and time zone data.
El error más común al conservar DateTime valores como cadenas es basarse en las convenciones de formato de la referencia cultural predeterminada o actual.The most common error made when persisting DateTime values as strings is to rely on the formatting conventions of the default or current culture. Se producen problemas si la referencia cultural actual es diferente al guardar y restaurar las cadenas.Problems arise if the current culture is different when saving and restoring the strings. En el ejemplo siguiente se muestran estos problemas.The following example illustrates these problems. Guarda cinco fechas mediante las convenciones de formato de la referencia cultural actual, que en este caso es el inglés (Estados Unidos).It saves five dates using the formatting conventions of the current culture, which in this case is English (United States). Restaura las fechas mediante las convenciones de formato de una referencia cultural diferente, que en este caso es el inglés (Gran Bretaña).It restores the dates using the formatting conventions of a different culture, which in this case is English (Great Britain). Dado que las convenciones de formato de las dos referencias culturales son diferentes, no se pueden restaurar dos de las fechas y las tres fechas restantes se interpretan de forma incorrecta.Because the formatting conventions of the two cultures are different, two of the dates can't be restored, and the remaining three dates are interpreted incorrectly. Además, si los valores de fecha y hora originales representan momentos únicos en el tiempo, los tiempos de restauración son incorrectos porque se pierde la información de zona horaria.Also, if the original date and time values represent single moments in time, the restored times are incorrect because time zone information is lost.
[!code-csharpSystem.DateTime.Persistence#1][!code-csharpSystem.DateTime.Persistence#1]
Public Sub PersistAsLocalStrings()
SaveDatesAsStrings()
RestoreDatesAsStrings()
End Sub
Private Sub SaveDatesAsStrings()
Dim dates As Date() = {#6/14/2014 6:32AM#, #7/10/2014 11:49PM#,
#1/10/2015 1:16AM#, #12/20/2014 9:45PM#,
#6/2/2014 3:14PM#}
Dim output As String = Nothing
Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
For ctr As Integer = 0 To dates.Length - 1
Console.WriteLine(dates(ctr).ToString("f"))
output += dates(ctr).ToString() + If(ctr <> dates.Length - 1, "|", "")
Next
Dim sw As New StreamWriter(filenameTxt)
sw.Write(output)
sw.Close()
Console.WriteLine("Saved dates...")
End Sub
Private Sub RestoreDatesAsStrings()
TimeZoneInfo.ClearCachedData()
Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
Dim sr As New StreamReader(filenameTxt)
Dim inputValues As String() = sr.ReadToEnd().Split({"|"c}, StringSplitOptions.RemoveEmptyEntries)
sr.Close()
Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
For Each inputValue In inputValues
Dim dateValue As Date
If DateTime.TryParse(inputValue, dateValue) Then
Console.WriteLine($"'{inputValue}' --> {dateValue:f}")
Else
Console.WriteLine($"Cannot parse '{inputValue}'")
End If
Next
Console.WriteLine("Restored dates...")
End Sub
' When saved on an en-US system, the example displays the following output:
' Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
' The dates on an en-US system:
' Saturday, June 14, 2014 6:32 AM
' Thursday, July 10, 2014 11:49 PM
' Saturday, January 10, 2015 1:16 AM
' Saturday, December 20, 2014 9:45 PM
' Monday, June 02, 2014 3:14 PM
' Saved dates...
'
' When restored on an en-GB system, the example displays the following output:
' Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
' The dates on an en-GB system:
' Cannot parse '6/14/2014 6:32:00 AM'
' '7/10/2014 11:49:00 PM' --> 07 October 2014 23:49
' '1/10/2015 1:16:00 AM' --> 01 October 2015 01:16
' Cannot parse '12/20/2014 9:45:00 PM'
' '6/2/2014 3:14:00 PM' --> 06 February 2014 15:14
' Restored dates...
Para realizar un recorrido de ida y vuelta DateTime correctamente, siga estos pasos:To round-trip DateTime values successfully, follow these steps:
- Si los valores representan un solo instante de tiempo, conviértalos de la hora local a la hora UTC llamando al ToUniversalTime método.If the values represent single moments of time, convert them from the local time to UTC by calling the ToUniversalTime method.
- Convierta las fechas en sus representaciones de cadena mediante una llamada a la ToString(String, IFormatProvider) sobrecarga de o String.Format(IFormatProvider, String, Object[]) .Convert the dates to their string representations by calling the ToString(String, IFormatProvider) or String.Format(IFormatProvider, String, Object[]) overload. Use las convenciones de formato de la referencia cultural de todos los idiomas especificando CultureInfo.InvariantCulture como
providerargumento.Use the formatting conventions of the invariant culture by specifying CultureInfo.InvariantCulture as theproviderargument. Especifique que el valor debe realizarse mediante la cadena de formato estándar "O" o "R".Specify that the value should round-trip by using the "O" or "R" standard format string.
Para restaurar los valores conservados DateTime sin pérdida de datos, siga estos pasos:To restore the persisted DateTime values without data loss, follow these steps:
- Analice los datos mediante una llamada a la ParseExact sobrecarga de o TryParseExact .Parse the data by calling the ParseExact or TryParseExact overload. Especifique CultureInfo.InvariantCulture como
providerargumento y use la misma cadena de formato estándar que usó para elformatargumento durante la conversión.Specify CultureInfo.InvariantCulture as theproviderargument, and use the same standard format string you used for theformatargument during conversion. Incluya el DateTimeStyles.RoundtripKind valor en elstylesargumento.Include the DateTimeStyles.RoundtripKind value in thestylesargument. - Si los DateTime valores representan momentos únicos en el tiempo, llame al ToLocalTime método para convertir la fecha analizada de la hora UTC a la hora local.If the DateTime values represent single moments in time, call the ToLocalTime method to convert the parsed date from UTC to local time.
En el ejemplo siguiente se usa la referencia cultural de todos los idiomas y la cadena de formato estándar "O" para asegurarse de que DateTime los valores guardados y restaurados representan el mismo momento en el tiempo, independientemente del sistema, la referencia cultural o la zona horaria de los sistemas de origen y de destino.The following example uses the invariant culture and the "O" standard format string to ensure that DateTime values saved and restored represent the same moment in time regardless of the system, culture, or time zone of the source and target systems.
[!code-csharpSystem.DateTime.Persistence#2][!code-csharpSystem.DateTime.Persistence#2]
Public Sub PersistAsInvariantStrings()
SaveDatesAsInvariantStrings()
RestoreDatesAsInvariantStrings()
End Sub
Private Sub SaveDatesAsInvariantStrings()
Dim dates As Date() = {#6/14/2014 6:32AM#, #7/10/2014 11:49PM#,
#1/10/2015 1:16AM#, #12/20/2014 9:45PM#,
#6/2/2014 3:14PM#}
Dim output As String = Nothing
Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
For ctr As Integer = 0 To dates.Length - 1
Console.WriteLine(dates(ctr).ToString("f"))
output += dates(ctr).ToUniversalTime().ToString("O", CultureInfo.InvariantCulture) +
If(ctr <> dates.Length - 1, "|", "")
Next
Dim sw As New StreamWriter(filenameTxt)
sw.Write(output)
sw.Close()
Console.WriteLine("Saved dates...")
End Sub
Private Sub RestoreDatesAsInvariantStrings()
TimeZoneInfo.ClearCachedData()
Console.WriteLine("Current Time Zone: {0}",
TimeZoneInfo.Local.DisplayName)
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
Dim sr As New StreamReader(filenameTxt)
Dim inputValues As String() = sr.ReadToEnd().Split({"|"c}, StringSplitOptions.RemoveEmptyEntries)
sr.Close()
Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
For Each inputValue In inputValues
Dim dateValue As Date
If DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, dateValue) Then
Console.WriteLine($"'{inputValue}' --> {dateValue.ToLocalTime():f}")
Else
Console.WriteLine($"Cannot parse '{inputValue}'")
End If
Next
Console.WriteLine("Restored dates...")
End Sub
' When saved on an en-US system, the example displays the following output:
' Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
' The dates on an en-US system:
' Saturday, June 14, 2014 6:32 AM
' Thursday, July 10, 2014 11:49 PM
' Saturday, January 10, 2015 1:16 AM
' Saturday, December 20, 2014 9:45 PM
' Monday, June 02, 2014 3:14 PM
' Saved dates...
'
' When restored on an en-GB system, the example displays the following output:
' Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
' The dates on an en-GB system:
' '2014-06-14T13:32:00.0000000Z' --> 14 June 2014 14:32
' '2014-07-11T06:49:00.0000000Z' --> 11 July 2014 07:49
' '2015-01-10T09:16:00.0000000Z' --> 10 January 2015 09:16
' '2014-12-21T05:45:00.0000000Z' --> 21 December 2014 05:45
' '2014-06-02T22:14:00.0000000Z' --> 02 June 2014 23:14
' Restored dates...
Almacenar valores como enterosPersisting values as integers
Puede conservar una fecha y hora como un Int64 valor que represente un número de pasos.You can persist a date and time as an Int64 value that represents a number of ticks. En este caso, no tiene que tener en cuenta la referencia cultural de los sistemas en los que los DateTime valores se conservan y se restauran.In this case, you don't have to consider the culture of the systems the DateTime values are persisted and restored on.
Para conservar un DateTime valor como un entero:To persist a DateTime value as an integer:
- Si los DateTime valores representan momentos únicos en el tiempo, conviértalos en UTC llamando al ToUniversalTime método.If the DateTime values represent single moments in time, convert them to UTC by calling the ToUniversalTime method.
- Recupere el número de pasos representados por el DateTime valor de su Ticks propiedad.Retrieve the number of ticks represented by the DateTime value from its Ticks property.
Para restaurar un DateTime valor que se ha guardado como un entero:To restore a DateTime value that has been persisted as an integer:
- Cree una instancia de un nuevo DateTime objeto pasando el Int64 valor al DateTime(Int64) constructor.Instantiate a new DateTime object by passing the Int64 value to the DateTime(Int64) constructor.
- Si el DateTime valor representa un único momento en el tiempo, conviértalo de la hora UTC a la hora local llamando al ToLocalTime método.If the DateTime value represents a single moment in time, convert it from UTC to the local time by calling the ToLocalTime method.
En el ejemplo siguiente se conserva una matriz de DateTime valores como enteros en un sistema de la zona horaria del Pacífico de EE. UU.The following example persists an array of DateTime values as integers on a system in the U.S. Pacific Time zone. Lo restaura en un sistema de la zona UTC.It restores it on a system in the UTC zone. El archivo que contiene los enteros incluye un Int32 valor que indica el número total de Int64 valores que siguen inmediatamente a él.The file that contains the integers includes an Int32 value that indicates the total number of Int64 values that immediately follow it.
[!code-csharpSystem.DateTime.Persistence#3][!code-csharpSystem.DateTime.Persistence#3]
Public Sub PersistAsIntegers()
SaveDatesAsIntegers()
RestoreDatesAsIntegers()
End Sub
Private Sub SaveDatesAsIntegers()
Dim dates As Date() = {#6/14/2014 6:32AM#, #7/10/2014 11:49PM#,
#1/10/2015 1:16AM#, #12/20/2014 9:45PM#,
#6/2/2014 3:14PM#}
Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
Dim ticks(dates.Length - 1) As Long
For ctr As Integer = 0 To dates.Length - 1
Console.WriteLine(dates(ctr).ToString("f"))
ticks(ctr) = dates(ctr).ToUniversalTime().Ticks
Next
Dim fs As New FileStream(filenameInts, FileMode.Create)
Dim bw As New BinaryWriter(fs)
bw.Write(ticks.Length)
For Each tick In ticks
bw.Write(tick)
Next
bw.Close()
Console.WriteLine("Saved dates...")
End Sub
Private Sub RestoreDatesAsIntegers()
TimeZoneInfo.ClearCachedData()
Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
Dim fs As New FileStream(filenameInts, FileMode.Open)
Dim br As New BinaryReader(fs)
Dim items As Integer
Dim dates As DateTime()
Try
items = br.ReadInt32()
ReDim dates(items - 1)
For ctr As Integer = 0 To items - 1
Dim ticks As Long = br.ReadInt64()
dates(ctr) = New DateTime(ticks).ToLocalTime()
Next
Catch e As EndOfStreamException
Console.WriteLine("File corruption detected. Unable to restore data...")
Exit Sub
Catch e As IOException
Console.WriteLine("Unspecified I/O error. Unable to restore data...")
Exit Sub
Catch e As OutOfMemoryException 'Thrown in array initialization.
Console.WriteLine("File corruption detected. Unable to restore data...")
Exit Sub
Finally
br.Close()
End Try
Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
For Each value In dates
Console.WriteLine(value.ToString("f"))
Next
Console.WriteLine("Restored dates...")
End Sub
' When saved on an en-US system, the example displays the following output:
' Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
' The dates on an en-US system:
' Saturday, June 14, 2014 6:32 AM
' Thursday, July 10, 2014 11:49 PM
' Saturday, January 10, 2015 1:16 AM
' Saturday, December 20, 2014 9:45 PM
' Monday, June 02, 2014 3:14 PM
' Saved dates...
'
' When restored on an en-GB system, the example displays the following output:
' Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
' The dates on an en-GB system:
' 14 June 2014 14:32
' 11 July 2014 07:49
' 10 January 2015 09:16
' 21 December 2014 05:45
' 02 June 2014 23:14
' Restored dates...
Serializar valores DateTimeSerializing DateTime values
Puede conservar DateTime los valores mediante la serialización en una secuencia o archivo y, a continuación, restaurarlos a través de la deserialización.You can persist DateTime values through serialization to a stream or file, and then restore them through deserialization. DateTime los datos se serializan en algún formato de objeto especificado.DateTime data is serialized in some specified object format. Los objetos se restauran cuando se deserializan.The objects are restored when they are deserialized. Un formateador o serializador, como XmlSerializer o BinaryFormatter , controla el proceso de serialización y deserialización.A formatter or serializer, such as XmlSerializer or BinaryFormatter, handles the process of serialization and deserialization. Para obtener más información sobre la serialización y los tipos de serialización admitidos por el .NET Framework, vea serialización.For more information about serialization and the types of serialization supported by the .NET Framework, see Serialization.
En el ejemplo siguiente se usa la XmlSerializer clase para serializar y deserializar DateTime valores.The following example uses the XmlSerializer class to serialize and deserialize DateTime values. Los valores representan todos los días de año bisiestos del siglo XXI.The values represent all leap year days in the twenty-first century. La salida representa el resultado si el ejemplo se ejecuta en un sistema cuya referencia cultural actual es inglés (Gran Bretaña).The output represents the result if the example is run on a system whose current culture is English (Great Britain). Dado que ha deserializado el DateTime propio objeto, el código no tiene que administrar las diferencias culturales en los formatos de fecha y hora.Because you've deserialized the DateTime object itself, the code doesn't have to handle cultural differences in date and time formats.
[!code-csharpSystem.DateTime.Persistence#4][!code-csharpSystem.DateTime.Persistence#4]
Public Sub PersistAsXml()
' Serialize the data.
Dim leapYears As New List(Of DateTime)()
For year As Integer = 2000 To 2100 Step 4
If Date.IsLeapYear(year) Then
leapYears.Add(New Date(year, 2, 29))
End If
Next
Dim dateArray As DateTime() = leapYears.ToArray()
Dim serializer As New XmlSerializer(dateArray.GetType())
Dim sw As TextWriter = New StreamWriter(filenameXml)
Try
serializer.Serialize(sw, dateArray)
Catch e As InvalidOperationException
Console.WriteLine(e.InnerException.Message)
Finally
If sw IsNot Nothing Then sw.Close()
End Try
' Deserialize the data.
Dim deserializedDates As Date()
Using fs As New FileStream(filenameXml, FileMode.Open)
deserializedDates = CType(serializer.Deserialize(fs), Date())
End Using
' Display the dates.
Console.WriteLine($"Leap year days from 2000-2100 on an {Thread.CurrentThread.CurrentCulture.Name} system:")
Dim nItems As Integer
For Each dat In deserializedDates
Console.Write($" {dat:d} ")
nItems += 1
If nItems Mod 5 = 0 Then Console.WriteLine()
Next
End Sub
' The example displays the following output:
' Leap year days from 2000-2100 on an en-GB system:
' 29/02/2000 29/02/2004 29/02/2008 29/02/2012 29/02/2016
' 29/02/2020 29/02/2024 29/02/2028 29/02/2032 29/02/2036
' 29/02/2040 29/02/2044 29/02/2048 29/02/2052 29/02/2056
' 29/02/2060 29/02/2064 29/02/2068 29/02/2072 29/02/2076
' 29/02/2080 29/02/2084 29/02/2088 29/02/2092 29/02/2096
En el ejemplo anterior no se incluye información de hora.The previous example doesn't include time information. Si un DateTime valor representa un momento dado y se expresa como una hora local, conviértalo de la hora local a UTC antes de serializarlo llamando al ToUniversalTime método.If a DateTime value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the ToUniversalTime method. Después de deserializarlo, conviértalo de la hora UTC a la hora local llamando al ToLocalTime método.After you deserialize it, convert it from UTC to local time by calling the ToLocalTime method. En el ejemplo siguiente se usa la BinaryFormatter clase para serializar los DateTime datos de un sistema de la zona horaria estándar del Pacífico de EE. UU. y para deserializarlo en un sistema de la zona estándar de EE. UU.The following example uses the BinaryFormatter class to serialize DateTime data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the U.S. Central Standard zone.
[!code-csharpSystem.DateTime.Persistence#5][!code-csharpSystem.DateTime.Persistence#5]
Public Sub PersistBinary()
SaveDatesBinary()
RestoreDatesBinary()
End Sub
Private Sub SaveDatesBinary()
Dim dates As Date() = {#6/14/2014 6:32AM#, #7/10/2014 11:49PM#,
#1/10/2015 1:16AM#, #12/20/2014 9:45PM#,
#6/2/2014 3:14PM#}
Dim fs As New FileStream(filenameBin, FileMode.Create)
Dim bin As New BinaryFormatter()
Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
Console.WriteLine("The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
For ctr As Integer = 0 To dates.Length - 1
Console.WriteLine(dates(ctr).ToString("f"))
dates(ctr) = dates(ctr).ToUniversalTime()
Next
bin.Serialize(fs, dates)
fs.Close()
Console.WriteLine("Saved dates...")
End Sub
Private Sub RestoreDatesBinary()
TimeZoneInfo.ClearCachedData()
Console.WriteLine("Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
Dim fs As New FileStream(filenameBin, FileMode.Open)
Dim bin As New BinaryFormatter()
Dim dates As DateTime() = DirectCast(bin.Deserialize(fs), Date())
fs.Close()
Console.WriteLine("The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
For Each value In dates
Console.WriteLine(value.ToLocalTime().ToString("f"))
Next
Console.WriteLine("Restored dates...")
End Sub
' When saved on an en-US system, the example displays the following output:
' Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
' The dates on an en-US system:
' Saturday, June 14, 2014 6:32 AM
' Thursday, July 10, 2014 11:49 PM
' Saturday, January 10, 2015 1:16 AM
' Saturday, December 20, 2014 9:45 PM
' Monday, June 02, 2014 3:14 PM
' Saved dates...
'
' When restored on an en-GB system, the example displays the following output:
' Current Time Zone: (UTC-6:00) Central Time (US & Canada)
' The dates on an en-GB system:
' 14 June 2014 08:32
' 11 July 2014 01:49
' 10 January 2015 03:16
' 20 December 2014 11:45
' 02 June 2014 17:14
' Restored dates...
Serializar datos de zona horaria y de fecha y horaSerializing DateTime and time zone data
En los ejemplos anteriores se supone que los DateTime valores se expresan como horas locales.The previous examples all assumed that DateTime values are expressed as local times. El código convirtió los valores entre la hora UTC y la hora local para que reflejen el mismo momento en el tiempo en los sistemas de origen y de destino.The code converted the values between UTC and local time so they reflect the same moment in time on the source and target systems. DateTime los valores también pueden reflejar momentos en el tiempo en una zona horaria distinta de local y UTC.DateTime values may also reflect moments in time in a time zone other than local and UTC. Dado que la DateTime estructura no tiene en cuenta la zona horaria, tiene que serializar el DateTime valor y el TimeZoneInfo objeto que representa su zona horaria.Because the DateTime structure is not time zone-aware, you have to serialize both the DateTime value and the TimeZoneInfo object that represents its time zone. Cree un tipo cuyos campos incluyan tanto el DateTime valor como su zona horaria.Create a type whose fields include both the DateTime value and its time zone. En el ejemplo siguiente se define una DateWithTimeZone estructura.The following example defines a DateWithTimeZone structure.
[!code-csharpSystem.DateTime.Persistence#6][!code-csharpSystem.DateTime.Persistence#6]
Namespace DateTimeExtensions
<Serializable> Public Structure DateWithTimeZone
Private tz As TimeZoneInfo
Private dt As DateTime
Public Sub New(dateValue As DateTime, timeZone As TimeZoneInfo)
dt = dateValue
tz = If(timeZone, TimeZoneInfo.Local)
End Sub
Public Property TimeZone As TimeZoneInfo
Get
Return tz
End Get
Set
tz = Value
End Set
End Property
Public Property DateTime As Date
Get
Return dt
End Get
Set
dt = Value
End Set
End Property
End Structure
End Namespace
Importante
La DateWithTimeZone estructura se usa en los dos ejemplos siguientes, que serializan y deserializan una matriz de DateWithTimeZone objetos.The DateWithTimeZone structure is used in the next two examples, which serialize and deserialize an array of DateWithTimeZone objects. Puede ver el código fuente de todo el conjunto de ejemplos de este artículo en Visual Basic o C# desde el repositorio de documentos en github.You can view the source for the entire set of examples from this article in either Visual Basic or C# from the docs repository on GitHub.
Mediante el uso de la DateWithTimeZone estructura, puede conservar la fecha y la hora junto con la información de zona horaria.By using the DateWithTimeZone structure, you can then persist date and time along with time zone information. En el ejemplo siguiente se usa la BinaryFormatter clase para serializar una matriz de DateWithTimeZone objetos.The following example uses the BinaryFormatter class to serialize an array of DateWithTimeZone objects.
public static void SaveDateWithTimeZone()
{
DateWithTimeZone[] dates = { new DateWithTimeZone(new DateTime(2014, 8, 9, 19, 30, 0),
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
new DateWithTimeZone(new DateTime(2014, 8, 15, 19, 0, 0),
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")),
new DateWithTimeZone(new DateTime(2014, 8, 22, 19, 30, 0),
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
new DateWithTimeZone(new DateTime(2014, 8, 28, 19, 0, 0),
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")) };
var fs = new FileStream(@".\Schedule.bin", FileMode.Create);
var formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, dates);
// Display dates.
foreach (var date in dates)
{
TimeZoneInfo tz = date.TimeZone;
Console.WriteLine($"{date.DateTime} {(tz.IsDaylightSavingTime(date.DateTime) ? tz.DaylightName : tz.StandardName)}");
}
}
catch (SerializationException e)
{
Console.WriteLine($"Serialization failed. Reason: {e.Message}");
}
finally
{
if (fs != null) fs.Close();
}
}
// The example displays the following output:
// 8/9/2014 7:30:00 PM Eastern Daylight Time
// 8/15/2014 7:00:00 PM Pacific Daylight Time
// 8/22/2014 7:30:00 PM Eastern Daylight Time
// 8/28/2014 7:00:00 PM Eastern Daylight Time
Public Sub SaveDateWithTimeZone()
Dim dates As DateWithTimeZone() = {New DateWithTimeZone(#8/9/2014 7:30PM#,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
New DateWithTimeZone(#8/15/2014 7:00PM#,
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")),
New DateWithTimeZone(#8/22/2014 7:30PM#,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
New DateWithTimeZone(#8/28/2014 7:00PM#,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))}
Dim fs As New FileStream(".\Schedule.bin", FileMode.Create)
Dim formatter As New BinaryFormatter()
Try
formatter.Serialize(fs, dates)
Catch e As SerializationException
Console.WriteLine($"Serialization failed. Reason: {e.Message}")
Finally
If fs IsNot Nothing Then fs.Close()
End Try
' Display dates.
For Each dateInfo In dates
Dim tz As TimeZoneInfo = dateInfo.TimeZone
Console.WriteLine($"{dateInfo.DateTime} {If(tz.IsDaylightSavingTime(dateInfo.DateTime), tz.DaylightName, tz.StandardName)}")
Next
End Sub
' The example displays the following output:
' 8/9/2014 7:30:00 PM Eastern Daylight Time
' 8/15/2014 7:00:00 PM Pacific Daylight Time
' 8/22/2014 7:30:00 PM Eastern Daylight Time
' 8/28/2014 7:00:00 PM Eastern Daylight Time
En el ejemplo siguiente se llama al BinaryFormatter.Deserialize método para deserializarlo.The following example then calls the BinaryFormatter.Deserialize method to deserialize it.
public static void RestoreDateWithTimeZone()
{
const string filename = @".\Schedule.bin";
FileStream fs;
if (File.Exists(filename))
{
fs = new FileStream(filename, FileMode.Open);
}
else
{
Console.WriteLine("Unable to find file to deserialize.");
return;
}
var formatter = new BinaryFormatter();
DateWithTimeZone[] dates;
try
{
dates = (DateWithTimeZone[])formatter.Deserialize(fs);
// Display dates.
foreach (var date in dates)
{
TimeZoneInfo tz = date.TimeZone;
Console.WriteLine($"{ date.DateTime} {(tz.IsDaylightSavingTime(date.DateTime) ? tz.DaylightName : tz.StandardName)}");
}
}
catch (SerializationException e)
{
Console.WriteLine($"Deserialization failed. Reason: {e.Message}");
}
finally
{
if (fs != null) fs.Close();
}
}
// The example displays the following output:
// 8/9/2014 7:30:00 PM Eastern Daylight Time
// 8/15/2014 7:00:00 PM Pacific Daylight Time
// 8/22/2014 7:30:00 PM Eastern Daylight Time
// 8/28/2014 7:00:00 PM Eastern Daylight Time
Public Sub RestoreDateWithTimeZone()
Dim fs As FileStream
If File.Exists(filename) Then
fs = New FileStream(filename, FileMode.Open)
Else
Console.WriteLine("Unable to find file to deserialize.")
Exit Sub
End If
Dim formatter As New BinaryFormatter()
Dim dates As DateWithTimeZone ()= Nothing
Try
dates = DirectCast(formatter.Deserialize(fs), DateWithTimeZone())
' Display dates.
For Each dateInfo In dates
Dim tz As TimeZoneInfo = dateInfo.TimeZone
Console.WriteLine($"{dateInfo.DateTime} {If(tz.IsDaylightSavingTime(dateInfo.DateTime), tz.DaylightName, tz.StandardName)}")
Next
Catch e As SerializationException
Console.WriteLine("Deserialization failed. Reason: {e.Message}")
Finally
If fs IsNot Nothing Then fs.Close()
End Try
End Sub
' The example displays the following output:
' 8/9/2014 7:30:00 PM Eastern Daylight Time
' 8/15/2014 7:00:00 PM Pacific Daylight Time
' 8/22/2014 7:30:00 PM Eastern Daylight Time
' 8/28/2014 7:00:00 PM Eastern Daylight Time
DateTime frente a TimeSpanDateTime vs. TimeSpan
Los DateTime TimeSpan tipos de valor y difieren en que un DateTime representa un instante en el tiempo, mientras que TimeSpan representa un intervalo de tiempo.The DateTime and TimeSpan value types differ in that a DateTime represents an instant in time whereas a TimeSpan represents a time interval. Puede restar una instancia de DateTime de otra para obtener un TimeSpan objeto que represente el intervalo de tiempo entre ellas.You can subtract one instance of DateTime from another to obtain a TimeSpan object that represents the time interval between them. O bien, puede Agregar un positivo TimeSpan al actual DateTime para obtener un DateTime valor que represente una fecha futura.Or you could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future date.
Puede Agregar o restar un intervalo de tiempo de un DateTime objeto.You can add or subtract a time interval from a DateTime object. Los intervalos de tiempo pueden ser negativos o positivos, y se pueden expresar en unidades como TICs, segundos o como un TimeSpan objeto.Time intervals can be negative or positive, and they can be expressed in units such as ticks, seconds, or as a TimeSpan object.
Comparar la igualdad dentro de la toleranciaComparing for equality within tolerance
Las comparaciones de igualdad de DateTime valores son exactas.Equality comparisons for DateTime values are exact. Esto significa que dos valores se deben expresar como el mismo número de pasos que se consideran iguales.That means two values must be expressed as the same number of ticks to be considered equal. Esa precisión suele ser innecesaria o incluso incorrecta para muchas aplicaciones.That precision is often unnecessary or even incorrect for many applications. A menudo, desea probar si los DateTime objetos son aproximadamente iguales.Often, you want to test if DateTime objects are roughly equal.
En el ejemplo siguiente se muestra cómo comparar valores equivalentes aproximadamente DateTime .The following example demonstrates how to compare roughly equivalent DateTime values. Acepta un pequeño margen de diferencia al declararlos iguales.It accepts a small margin of difference when declaring them equal.
[!code-csharpSystem.DateTime.Comparisons#1][!code-csharpSystem.DateTime.Comparisons#1]
Public Shared Function RoughlyEquals(time As DateTime, timeWithWindow As DateTime,
windowInSeconds As Integer,
frequencyInSeconds As Integer) As Boolean
Dim delta As Long = (timeWithWindow.Subtract(time)).TotalSeconds _
Mod frequencyInSeconds
If delta > windowInSeconds Then
delta = frequencyInSeconds - delta
End If
Return Math.Abs(delta) < windowInSeconds
End Function
Public Shared Sub TestRoughlyEquals()
Dim window As Integer = 10
Dim freq As Integer = 60 * 60 * 2 ' 2 hours;
Dim d1 As DateTime = DateTime.Now
Dim d2 As DateTime = d1.AddSeconds(2 * window)
Dim d3 As DateTime = d1.AddSeconds(-2 * window)
Dim d4 As DateTime = d1.AddSeconds(window / 2)
Dim d5 As DateTime = d1.AddSeconds(-window / 2)
Dim d6 As DateTime = d1.AddHours(2).AddSeconds(2 * window)
Dim d7 As DateTime = d1.AddHours(2).AddSeconds(-2 * window)
Dim d8 As DateTime = d1.AddHours(2).AddSeconds(window / 2)
Dim d9 As DateTime = d1.AddHours(2).AddSeconds(-window / 2)
Console.WriteLine($"d1 ({d1}) ~= d1 ({d1}): {RoughlyEquals(d1, d1, window, freq)}")
Console.WriteLine($"d1 ({d1}) ~= d2 ({d2}): {RoughlyEquals(d1, d2, window, freq)}")
Console.WriteLine($"d1 ({d1}) ~= d3 ({d3}): {RoughlyEquals(d1, d3, window, freq)}")
Console.WriteLine($"d1 ({d1}) ~= d4 ({d4}): {RoughlyEquals(d1, d4, window, freq)}")
Console.WriteLine($"d1 ({d1}) ~= d5 ({d5}): {RoughlyEquals(d1, d5, window, freq)}")
Console.WriteLine($"d1 ({d1}) ~= d6 ({d6}): {RoughlyEquals(d1, d6, window, freq)}")
Console.WriteLine($"d1 ({d1}) ~= d7 ({d7}): {RoughlyEquals(d1, d7, window, freq)}")
Console.WriteLine($"d1 ({d1}) ~= d8 ({d8}): {RoughlyEquals(d1, d8, window, freq)}")
Console.WriteLine($"d1 ({d1}) ~= d9 ({d9}): {RoughlyEquals(d1, d9, window, freq)}")
End Sub
' The example displays output similar to the following:
' d1 (1/28/2010 9:01:26 PM) ~= d1 (1/28/2010 9:01:26 PM): True
' d1 (1/28/2010 9:01:26 PM) ~= d2 (1/28/2010 9:01:46 PM): False
' d1 (1/28/2010 9:01:26 PM) ~= d3 (1/28/2010 9:01:06 PM): False
' d1 (1/28/2010 9:01:26 PM) ~= d4 (1/28/2010 9:01:31 PM): True
' d1 (1/28/2010 9:01:26 PM) ~= d5 (1/28/2010 9:01:21 PM): True
' d1 (1/28/2010 9:01:26 PM) ~= d6 (1/28/2010 11:01:46 PM): False
' d1 (1/28/2010 9:01:26 PM) ~= d7 (1/28/2010 11:01:06 PM): False
' d1 (1/28/2010 9:01:26 PM) ~= d8 (1/28/2010 11:01:31 PM): True
' d1 (1/28/2010 9:01:26 PM) ~= d9 (1/28/2010 11:01:21 PM): True
Consideraciones sobre la interoperabilidad COMCOM interop considerations
Un DateTime valor que se transfiere a una aplicación com, después se transfiere de nuevo a una aplicación administrada, se dice que se va a realizar un recorrido de ida y vuelta.A DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. Sin embargo, un DateTime valor que especifica solo una hora no realiza un recorrido de ida y vuelta como cabría esperar.However, a DateTime value that specifies only a time does not round-trip as you might expect.
Si solo se hace un recorrido de ida y vuelta, como 3 P.M., la fecha y hora finales es el 30 de diciembre de 1899 de la era cristianaIf you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. a las 3:00 P.M., en lugar del 1 de enero de 0001 de la era cristianaat 3:00 P.M., instead of January, 1, 0001 C.E. a las 3:00 P.M.at 3:00 P.M. El .NET Framework y COM suponen una fecha predeterminada cuando se especifica solo una hora.The .NET Framework and COM assume a default date when only a time is specified. Sin embargo, el sistema COM presupone una fecha base del 30 de diciembre de 1899 de la era cristiana, mientras que el .NET Framework presupone una fecha base de enero, 1, 0001 de la era cristiana.However, the COM system assumes a base date of December 30, 1899 C.E., while the .NET Framework assumes a base date of January, 1, 0001 C.E.
Cuando solo se pasa una hora del .NET Framework a COM, se realiza un procesamiento especial que convierte la hora al formato utilizado por COM.When only a time is passed from the .NET Framework to COM, special processing is performed that converts the time to the format used by COM. Cuando solo se pasa una hora desde COM al .NET Framework, no se realiza ningún procesamiento especial porque dañaría fechas y horas legítimas el 30 de diciembre de 1899.When only a time is passed from COM to the .NET Framework, no special processing is performed because that would corrupt legitimate dates and times on or before December 30, 1899. Si una fecha inicia el recorrido de ida y vuelta desde COM, el .NET Framework y COM conservan la fecha.If a date starts its round-trip from COM, the .NET Framework and COM preserve the date.
El comportamiento de los .NET Framework y COM significa que, si la aplicación hace un recorrido de ida y vuelta DateTime que solo especifica una hora, la aplicación debe recordar modificar u omitir la fecha errónea del DateTime objeto final.The behavior of the .NET Framework and COM means that if your application round-trips a DateTime that only specifies a time, your application must remember to modify or ignore the erroneous date from the final DateTime object.
Constructores
| DateTime(Int32, Int32, Int32) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes y día especificados.Initializes a new instance of the DateTime structure to the specified year, month, and day. |
| DateTime(Int32, Int32, Int32, Calendar) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes y día especificados para el calendario determinado.Initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar. |
| DateTime(Int32, Int32, Int32, Int32, Int32, Int32) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto y segundo especificados.Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second. |
| DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto y segundo especificados para el calendario indicado.Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second for the specified calendar. |
| DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo y hora universal coordinada (UTC) u hora local especificados.Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and Coordinated Universal Time (UTC) or local time. |
| DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo y milisegundo especificados.Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond. |
| DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo y milisegundo especificados para el calendario indicado.Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond for the specified calendar. |
| DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo, milisegundo, y hora universal coordinada (UTC) u hora local especificados para el calendario indicado.Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar. |
| DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) |
Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo, milisegundo y hora universal coordinada (UTC) u hora local especificados.Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time. |
| DateTime(Int64) |
Inicializa una nueva instancia de la estructura DateTime en un número de pasos especificado.Initializes a new instance of the DateTime structure to a specified number of ticks. |
| DateTime(Int64, DateTimeKind) |
Inicializa una nueva instancia de la estructura DateTime en el número de pasos y hora universal coordinada (UTC) u hora local especificados.Initializes a new instance of the DateTime structure to a specified number of ticks and to Coordinated Universal Time (UTC) or local time. |
Campos
| MaxValue |
Representa el mayor valor posible de DateTime.Represents the largest possible value of DateTime. Este campo es de solo lectura.This field is read-only. |
| MinValue |
Representa el menor valor posible de DateTime.Represents the smallest possible value of DateTime. Este campo es de solo lectura.This field is read-only. |
| UnixEpoch |
El valor de esta constante es equivalente a 00:00:00.0000000 UTC, 1 de enero de 1970, en el calendario gregoriano.The value of this constant is equivalent to 00:00:00.0000000 UTC, January 1, 1970, in the Gregorian calendar. UnixEpoch define el momento dado en el que la hora de Unix es igual a 0.UnixEpoch defines the point in time when Unix time is equal to 0. |
Propiedades
| Date |
Obtiene el componente correspondiente a la fecha de esta instancia.Gets the date component of this instance. |
| Day |
Obtiene el día del mes representado por esta instancia.Gets the day of the month represented by this instance. |
| DayOfWeek |
Obtiene el día de la semana representado por esta instancia.Gets the day of the week represented by this instance. |
| DayOfYear |
Obtiene el día del año representado por esta instancia.Gets the day of the year represented by this instance. |
| Hour |
Obtiene el componente correspondiente a la hora de la fecha representada por esta instancia.Gets the hour component of the date represented by this instance. |
| Kind |
Obtiene un valor que indica si la hora representada por esta instancia está basada en la hora local, en la hora universal coordinada (UTC), o en ninguna de ellas.Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. |
| Millisecond |
Obtiene el componente correspondiente a los milisegundos de la fecha representada por esta instancia.Gets the milliseconds component of the date represented by this instance. |
| Minute |
Obtiene el componente correspondiente a los minutos de la fecha representada por esta instancia.Gets the minute component of the date represented by this instance. |
| Month |
Obtiene el componente correspondiente al mes de la fecha representada por esta instancia.Gets the month component of the date represented by this instance. |
| Now |
Obtiene un objeto DateTime que se establece en la fecha y hora actual de este equipo, expresada como hora local.Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time. |
| Second |
Obtiene el componente correspondiente a los segundos de la fecha representada por esta instancia.Gets the seconds component of the date represented by this instance. |
| Ticks |
Obtiene el número de pasos que representan la fecha y hora de esta instancia.Gets the number of ticks that represent the date and time of this instance. |
| TimeOfDay |
Obtiene la hora del día para esta instancia.Gets the time of day for this instance. |
| Today |
Obtiene la fecha actual.Gets the current date. |
| UtcNow |
Obtiene un objeto DateTime que se establece en la fecha y hora actual del equipo, expresada como hora universal coordinada (UTC).Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC). |
| Year |
Obtiene el componente correspondiente al año de la fecha representada por esta instancia.Gets the year component of the date represented by this instance. |
Métodos
| Add(TimeSpan) |
Devuelve un nuevo objeto DateTime que suma el valor del objeto TimeSpan especificado al valor de esta instancia.Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance. |
| AddDays(Double) |
Devuelve un nuevo objeto DateTime que suma el número especificado de días al valor de esta instancia.Returns a new DateTime that adds the specified number of days to the value of this instance. |
| AddHours(Double) |
Devuelve un nuevo objeto DateTime que suma el número especificado de horas al valor de esta instancia.Returns a new DateTime that adds the specified number of hours to the value of this instance. |
| AddMilliseconds(Double) |
Devuelve un nuevo objeto DateTime que suma el número especificado de milisegundos al valor de esta instancia.Returns a new DateTime that adds the specified number of milliseconds to the value of this instance. |
| AddMinutes(Double) |
Devuelve un nuevo objeto DateTime que suma el número especificado de minutos al valor de esta instancia.Returns a new DateTime that adds the specified number of minutes to the value of this instance. |
| AddMonths(Int32) |
Devuelve un nuevo objeto DateTime que suma el número especificado de meses al valor de esta instancia.Returns a new DateTime that adds the specified number of months to the value of this instance. |
| AddSeconds(Double) |
Devuelve un nuevo objeto DateTime que suma el número especificado de segundos al valor de esta instancia.Returns a new DateTime that adds the specified number of seconds to the value of this instance. |
| AddTicks(Int64) |
Devuelve un nuevo objeto DateTime que suma el número especificado de pasos al valor de esta instancia.Returns a new DateTime that adds the specified number of ticks to the value of this instance. |
| AddYears(Int32) |
Devuelve un nuevo objeto DateTime que suma el número especificado de años al valor de esta instancia.Returns a new DateTime that adds the specified number of years to the value of this instance. |
| Compare(DateTime, DateTime) |
Compara dos instancias de DateTime y devuelve un entero que indica si la primera instancia es anterior, igual o posterior a la segunda instancia.Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. |
| CompareTo(DateTime) |
Compara el valor de esta instancia con un valor de DateTime especificado y devuelve un entero que indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado.Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value. |
| CompareTo(Object) |
Compara el valor de esta instancia con un objeto especificado que contiene un valor de DateTime especificado y devuelve un entero que indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado.Compares the value of this instance to a specified object that contains a specified DateTime value, and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value. |
| DaysInMonth(Int32, Int32) |
Devuelve el número de días del mes y año especificados.Returns the number of days in the specified month and year. |
| Equals(DateTime) |
Devuelve un valor que indica si el valor de esta instancia equivale al valor de la instancia de DateTime especificada.Returns a value indicating whether the value of this instance is equal to the value of the specified DateTime instance. |
| Equals(DateTime, DateTime) |
Devuelve un valor que indica si dos instancias de DateTime tienen el mismo valor de fecha y hora.Returns a value indicating whether two DateTime instances have the same date and time value. |
| Equals(Object) |
Devuelve un valor que indica si esta instancia equivale a un objeto especificado.Returns a value indicating whether this instance is equal to a specified object. |
| FromBinary(Int64) |
Deserializa un valor binario de 64 bits y vuelve a crear un objeto DateTime serializado original.Deserializes a 64-bit binary value and recreates an original serialized DateTime object. |
| FromFileTime(Int64) |
Convierte la hora de archivo de Windows especificada en una hora local equivalente.Converts the specified Windows file time to an equivalent local time. |
| FromFileTimeUtc(Int64) |
Convierte la hora de archivo de Windows especificada en una hora UTC equivalente.Converts the specified Windows file time to an equivalent UTC time. |
| FromOADate(Double) |
Devuelve un DateTime que equivale a la fecha de automatización OLE especificada.Returns a DateTime equivalent to the specified OLE Automation Date. |
| GetDateTimeFormats() |
Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por los especificadores de formato de fecha y hora estándar.Converts the value of this instance to all the string representations supported by the standard date and time format specifiers. |
| GetDateTimeFormats(Char) |
Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por el especificador de formato de fecha y hora estándar indicado.Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier. |
| GetDateTimeFormats(Char, IFormatProvider) |
Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por el especificador de formato de fecha y hora estándar y la información de formato específica de la referencia cultural especificados.Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier and culture-specific formatting information. |
| GetDateTimeFormats(IFormatProvider) |
Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por los especificadores de formato de fecha y hora estándar y la información de formato específica de la referencia cultural especificada.Converts the value of this instance to all the string representations supported by the standard date and time format specifiers and the specified culture-specific formatting information. |
| GetHashCode() |
Devuelve el código hash de esta instancia.Returns the hash code for this instance. |
| GetTypeCode() |
Devuelve el TypeCode para el tipo de valor DateTime.Returns the TypeCode for value type DateTime. |
| IsDaylightSavingTime() |
Indica si esta instancia de DateTime está dentro del intervalo del horario de verano de la zona horaria actual.Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone. |
| IsLeapYear(Int32) |
Devuelve una indicación en la que se precisa si el año especificado es bisiesto.Returns an indication whether the specified year is a leap year. |
| Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) |
Convierte un intervalo de memoria que contiene una representación de cadena de una fecha y hora en el objeto DateTime equivalente mediante la información de formato específica de la referencia cultural y un estilo de formato especificados.Converts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style. |
| Parse(String) |
Convierte la representación de cadena para una fecha y hora en su DateTime equivalente, usando las convenciones de la referencia cultural de subproceso especificada.Converts the string representation of a date and time to its DateTime equivalent by using the conventions of the current thread culture. |
| Parse(String, IFormatProvider) |
Convierte la representación de cadena para una fecha y hora en su DateTime equivalente, usando la información de formato específica de la referencia cultural especificada.Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information. |
| Parse(String, IFormatProvider, DateTimeStyles) |
Convierte la representación de cadena de una fecha y hora en el objeto DateTime equivalente, usando la información de formato específica de la referencia cultural y un estilo de formato especificados.Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style. |
| ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) |
Convierte la representación de intervalo especificada de una fecha y hora en su valor DateTime equivalente, mediante el formato, la información de formato específica de la referencia cultural y el estilo especificados.Converts the specified span representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. El formato de la representación de cadena debe coincidir exactamente con el formato especificado; de lo contrario, se produce una excepción.The format of the string representation must match the specified format exactly or an exception is thrown. |
| ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles) |
Convierte la representación de intervalo especificada de una fecha y hora en su valor DateTime equivalente, mediante la matriz especificada de formatos, información de formato específica de la referencia cultural y estilo.Converts the specified span representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. El formato de la representación de cadena debe coincidir exactamente con, al menos, uno de los formatos especificados; de lo contrario se produce una excepción.The format of the string representation must match at least one of the specified formats exactly or an exception is thrown. |
| ParseExact(String, String, IFormatProvider) |
Convierte la representación de cadena especificada de una fecha y hora en el objeto DateTime equivalente, usando la información de formato específica de la referencia cultural y el formato que se hayan especificado.Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.The format of the string representation must match the specified format exactly. |
| ParseExact(String, String, IFormatProvider, DateTimeStyles) |
Convierte la representación de cadena especificada de una fecha y hora en el objeto DateTime equivalente, usando el formato, la información de formato específica de la referencia cultural y el estilo especificados.Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. El formato de la representación de cadena debe coincidir exactamente con el formato especificado; de lo contrario, se produce una excepción.The format of the string representation must match the specified format exactly or an exception is thrown. |
| ParseExact(String, String[], IFormatProvider, DateTimeStyles) |
Convierte la representación de cadena especificada de una fecha y hora en el objeto DateTime equivalente, usando la matriz de formatos, la información de formato específica de la referencia cultural y el estilo especificados.Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. El formato de la representación de cadena debe coincidir exactamente con, al menos, uno de los formatos especificados; de lo contrario se produce una excepción.The format of the string representation must match at least one of the specified formats exactly or an exception is thrown. |
| SpecifyKind(DateTime, DateTimeKind) |
Crea un nuevo objeto DateTime que tiene el mismo número de pasos que el objeto DateTime especificado, pero en hora local, en hora universal coordinada (UTC) o en ninguna de ellas, según indique el valor de DateTimeKind especificado.Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value. |
| Subtract(DateTime) |
Devuelve un nuevo objeto TimeSpan que resta la fecha y hora especificadas del valor de esta instancia.Returns a new TimeSpan that subtracts the specified date and time from the value of this instance. |
| Subtract(TimeSpan) |
Devuelve un nuevo objeto DateTime que resta la duración especificada del valor de esta instancia.Returns a new DateTime that subtracts the specified duration from the value of this instance. |
| ToBinary() |
Serializa el objeto DateTime actual a un valor binario de 64 bits que se puede usar después para volver a crear el objeto DateTime.Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object. |
| ToFileTime() |
Convierte el valor del objeto DateTime actual en una hora de archivo de Windows.Converts the value of the current DateTime object to a Windows file time. |
| ToFileTimeUtc() |
Convierte el valor del objeto DateTime actual en una hora de archivo de Windows.Converts the value of the current DateTime object to a Windows file time. |
| ToLocalTime() |
Convierte el valor del objeto DateTime actual a la hora local.Converts the value of the current DateTime object to local time. |
| ToLongDateString() |
Convierte el valor del objeto DateTime actual en su representación de cadena de fecha larga equivalente.Converts the value of the current DateTime object to its equivalent long date string representation. |
| ToLongTimeString() |
Convierte el valor del objeto DateTime actual en su representación de cadena de hora larga equivalente.Converts the value of the current DateTime object to its equivalent long time string representation. |
| ToOADate() |
Convierte el valor de esta instancia en la fecha de Automation OLE equivalente.Converts the value of this instance to the equivalent OLE Automation date. |
| ToShortDateString() |
Convierte el valor del objeto DateTime actual en su representación de cadena de fecha corta equivalente.Converts the value of the current DateTime object to its equivalent short date string representation. |
| ToShortTimeString() |
Convierte el valor del objeto DateTime actual en su representación de cadena de hora corta equivalente.Converts the value of the current DateTime object to its equivalent short time string representation. |
| ToString() |
Convierte el valor del objeto DateTime actual en su representación de cadena equivalente mediante las convenciones de formato de la referencia cultural actual.Converts the value of the current DateTime object to its equivalent string representation using the formatting conventions of the current culture. |
| ToString(IFormatProvider) |
Convierte el valor del objeto DateTime actual en su representación de cadena equivalente usando la información de formato específica de la referencia cultural especificada.Converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information. |
| ToString(String) |
Convierte el valor del objeto DateTime actual en su representación de cadena equivalente mediante el formato especificado y las convenciones de formato de la referencia cultural actual.Converts the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture. |
| ToString(String, IFormatProvider) |
Convierte el valor del objeto DateTime actual en la representación de cadena equivalente usando el formato y la información de formato específica de la referencia cultural especificados.Converts the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information. |
| ToUniversalTime() |
Convierte el valor del objeto DateTime actual a la hora universal coordinada (UTC).Converts the value of the current DateTime object to Coordinated Universal Time (UTC). |
| TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) |
Intenta dar formato al valor de la instancia de fecha y hora actual en el intervalo de caracteres proporcionado.Tries to format the value of the current datetime instance into the provided span of characters. |
| TryParse(ReadOnlySpan<Char>, DateTime) |
Convierte el intervalo de caracteres especificado de una fecha y hora en su valor DateTime equivalente y devuelve un valor que indica si la conversión se ha realizado correctamente.Converts the specified char span of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded. |
| TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) |
Convierte la representación de intervalo de una fecha y hora en su valor DateTime equivalente mediante la información de formato de la referencia cultural y el estilo de formato especificados, y devuelve un valor que indica si la conversión se ha realizado correctamente.Converts the span representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded. |
| TryParse(String, DateTime) |
Convierte la representación de cadena especificada de una fecha y hora en el objeto DateTime equivalente y devuelve un valor que indica si la conversión se realizó correctamente.Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded. |
| TryParse(String, IFormatProvider, DateTimeStyles, DateTime) |
Convierte la representación de cadena especificada de una fecha y hora en su equivalente DateTime usando la información de formato de la referencia cultural y el estilo de formato especificados, y devuelve un valor que indica si la conversión tuvo éxito.Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded. |
| TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) |
Convierte la representación de intervalo especificada de una fecha y hora en su valor DateTime equivalente, mediante el formato, la información de formato específica de la referencia cultural y el estilo especificados.Converts the specified span representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.The format of the string representation must match the specified format exactly. El método devuelve un valor que indica si la conversión se realizó correctamente.The method returns a value that indicates whether the conversion succeeded. |
| TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles, DateTime) |
Convierte el intervalo de caracteres especificado de una fecha y hora en su valor DateTime equivalente y devuelve un valor que indica si la conversión se ha realizado correctamente.Converts the specified char span of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded. |
| TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) |
Convierte la representación de cadena especificada de una fecha y hora en el objeto DateTime equivalente, usando el formato, la información de formato específica de la referencia cultural y el estilo especificados.Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. El formato de la representación de cadena debe coincidir exactamente con el formato especificado.The format of the string representation must match the specified format exactly. El método devuelve un valor que indica si la conversión se realizó correctamente.The method returns a value that indicates whether the conversion succeeded. |
| TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) |
Convierte la representación de cadena especificada de una fecha y hora en el objeto DateTime equivalente, usando la matriz de formatos, la información de formato específica de la referencia cultural y el estilo especificados.Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. El formato de la representación de cadena debe coincidir exactamente con al menos uno de los formatos especificados.The format of the string representation must match at least one of the specified formats exactly. El método devuelve un valor que indica si la conversión se realizó correctamente.The method returns a value that indicates whether the conversion succeeded. |
Operadores
| Addition(DateTime, TimeSpan) |
Agrega un intervalo de tiempo especificado a una fecha y hora especificadas, generando una fecha y hora nuevas.Adds a specified time interval to a specified date and time, yielding a new date and time. |
| Equality(DateTime, DateTime) |
Determina si dos instancias especificadas de DateTime son iguales.Determines whether two specified instances of DateTime are equal. |
| GreaterThan(DateTime, DateTime) |
Determina si un DateTime especificado es posterior a otro DateTime especificado.Determines whether one specified DateTime is later than another specified DateTime. |
| GreaterThanOrEqual(DateTime, DateTime) |
Determina si un DateTime especificado representa una fecha y hora que es el igual o posterior a otro DateTime especificado.Determines whether one specified DateTime represents a date and time that is the same as or later than another specified DateTime. |
| Inequality(DateTime, DateTime) |
Determina si dos instancias especificadas de DateTime no son iguales.Determines whether two specified instances of DateTime are not equal. |
| LessThan(DateTime, DateTime) |
Determina si un DateTime especificado es anterior a otro DateTime especificado.Determines whether one specified DateTime is earlier than another specified DateTime. |
| LessThanOrEqual(DateTime, DateTime) |
Determina si un DateTime especificado representa una fecha y hora que es el igual o anterior a otro DateTime especificado.Determines whether one specified DateTime represents a date and time that is the same as or earlier than another specified DateTime. |
| Subtraction(DateTime, DateTime) |
Resta una fecha y hora especificadas de otra fecha y hora especificadas y devuelve un intervalo de tiempo.Subtracts a specified date and time from another specified date and time and returns a time interval. |
| Subtraction(DateTime, TimeSpan) |
Resta un intervalo de tiempo especificado de un valor de fecha y hora especificado y devuelve un nuevo valor de fecha y hora.Subtracts a specified time interval from a specified date and time and returns a new date and time. |
Implementaciones de interfaz explícitas
| IComparable.CompareTo(Object) |
Compara la instancia actual con otro objeto del mismo tipo y devuelve un entero que indica si la posición de la instancia actual es anterior, posterior o igual que la del otro objeto en el criterio de ordenación.Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. |
| IConvertible.GetTypeCode() |
Devuelve el TypeCode para esta instancia.Returns the TypeCode for this instance. |
| IConvertible.ToBoolean(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToByte(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToChar(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToDateTime(IFormatProvider) |
Devuelve el objeto DateTime actual.Returns the current DateTime object. |
| IConvertible.ToDecimal(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToDouble(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToInt16(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToInt32(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToInt64(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToSByte(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToSingle(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToType(Type, IFormatProvider) |
Convierte el objeto DateTime actual en un objeto de un tipo especificado.Converts the current DateTime object to an object of a specified type. |
| IConvertible.ToUInt16(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToUInt32(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| IConvertible.ToUInt64(IFormatProvider) |
No se admite esta conversión.This conversion is not supported. Cualquier intento de usar este método produce una excepción InvalidCastException.Attempting to use this method throws an InvalidCastException. |
| ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
Rellena un objeto SerializationInfo con los datos necesarios para serializar el objeto DateTime actual.Populates a SerializationInfo object with the data needed to serialize the current DateTime object. |
Se aplica a
Seguridad para subprocesos
Todos los miembros de este tipo son seguros para subprocesos.All members of this type are thread safe. Los miembros que parecen modificar el estado de la instancia devuelven realmente una nueva instancia inicializada con el nuevo valor.Members that appear to modify instance state actually return a new instance initialized with the new value. Como con cualquier otro tipo, la lectura y escritura en una variable compartida que contiene una instancia de este tipo debe estar protegida por un bloqueo para garantizar la seguridad para subprocesos.As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.
Consulte también
- DateTimeOffset
- TimeSpan
- Calendar
- GetUtcOffset(DateTime)
- TimeZoneInfo
- Elegir entre DateTime, DateTimeOffset, TimeSpan y TimeZoneInfoChoosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo
- Trabajar con calendariosWorking with Calendars
- Ejemplo: Utilidad de formato WinForms de .NET Core (C#)Sample: .NET Core WinForms Formatting Utility (C#)
- Ejemplo: Utilidad de formato WinForms de .NET Core (Visual Basic)Sample: .NET Core WinForms Formatting Utility (Visual Basic)