.NET Framework Class Library DateTimeOffset Structure Represents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC).
Namespace:
System
Assembly:
mscorlib (in mscorlib.dll)

Syntax
<SerializableAttribute> _
Public Structure DateTimeOffset _
Implements IComparable, IFormattable, ISerializable, IDeserializationCallback, _
IComparable(Of DateTimeOffset), IEquatable(Of DateTimeOffset)
[SerializableAttribute]
public struct DateTimeOffset : IComparable,
IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>,
IEquatable<DateTimeOffset>
[SerializableAttribute]
public value class DateTimeOffset : IComparable,
IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>,
IEquatable<DateTimeOffset>
[<Sealed>]
[<SerializableAttribute>]
type DateTimeOffset =
struct
interface IComparable
interface IFormattable
interface ISerializable
interface IDeserializationCallback
interface IComparable<DateTimeOffset>
interface IEquatable<DateTimeOffset>
end
The DateTimeOffset type exposes the following members.

Constructors
|
| Name | Description |
|---|
.gif) .gif) | DateTimeOffset(DateTime) | Initializes a new instance of the DateTimeOffset structure using the specified DateTime value. | .gif) .gif) | DateTimeOffset(DateTime, TimeSpan) | Initializes a new instance of the DateTimeOffset structure using the specified DateTime value and offset. | .gif) .gif) | DateTimeOffset(Int64, TimeSpan) | Initializes a new instance of the DateTimeOffset structure using the specified number of ticks and offset. | .gif) .gif) | DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) | Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, and offset. | .gif) .gif) | DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) | Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, millisecond, and offset. | .gif) .gif) | DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan) | Initializes a new instance of the DateTimeOffset structure using the specified year, month, day, hour, minute, second, millisecond, and offset of a specified calendar. | Top

Methods
|
| Name | Description |
|---|
.gif) .gif) | Add | Adds a specified time interval to a DateTimeOffset object. | .gif) .gif) | AddDays | Adds a specified number of whole and fractional days to the current DateTimeOffset object. | .gif) .gif) | AddHours | Adds a specified number of whole and fractional hours to the current DateTimeOffset object. | .gif) .gif) | AddMilliseconds | Adds a specified number of milliseconds to the current DateTimeOffset object. | .gif) .gif) | AddMinutes | Adds a specified number of whole and fractional minutes to the current DateTimeOffset object. | .gif) .gif) | AddMonths | Adds a specified number of months to the current DateTimeOffset object. | .gif) .gif) | AddSeconds | Adds a specified number of whole and fractional seconds to the current DateTimeOffset object. | .gif) .gif) | AddTicks | Adds a specified number of ticks to the current DateTimeOffset object. | .gif) .gif) | AddYears | Adds a specified number of years to the DateTimeOffset object. | .gif) .gif) .gif) | Compare | Compares two DateTimeOffset objects and indicates whether the first is earlier than the second, equal to the second, or later than the second. | .gif) .gif) | CompareTo | Compares the current DateTimeOffset object to a specified DateTimeOffset object and indicates whether the current object is earlier than, the same as, or later than the second DateTimeOffset object. | .gif) .gif) | Equals(DateTimeOffset) | Determines whether the current DateTimeOffset object represents the same point in time as a specified DateTimeOffset object. | .gif) .gif) | Equals(Object) | Determines whether a DateTimeOffset object represents the same point in time as a specified object. (Overrides ValueType..::.Equals(Object).) | .gif) .gif) .gif) | Equals(DateTimeOffset, DateTimeOffset) | Determines whether two specified DateTimeOffset objects represent the same point in time. | .gif) .gif) | EqualsExact | Determines whether the current DateTimeOffset object represents the same time and has the same offset as a specified DateTimeOffset object. | .gif) .gif) | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | .gif) .gif) | FromFileTime | Converts the specified Windows file time to an equivalent local time. | .gif) .gif) | GetHashCode | Returns the hash code for the current DateTimeOffset object. (Overrides ValueType..::.GetHashCode()()().) | .gif) .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) .gif) | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) .gif) | Parse(String) | Converts the specified string representation of a date, time, and offset to its DateTimeOffset equivalent. | .gif) .gif) .gif) | Parse(String, IFormatProvider) | Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified culture-specific format information. | .gif) .gif) .gif) | Parse(String, IFormatProvider, DateTimeStyles) | Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified culture-specific format information and formatting style. | .gif) .gif) .gif) | ParseExact(String, String, IFormatProvider) | Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly. | .gif) .gif) .gif) | ParseExact(String, String, IFormatProvider, DateTimeStyles) | Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. | .gif) .gif) .gif) | ParseExact(String, array<String>[]()[], IFormatProvider, DateTimeStyles) | Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified formats, culture-specific format information, and style. The format of the string representation must match one of the specified formats exactly. | .gif) .gif) | Subtract(DateTimeOffset) | Subtracts a DateTimeOffset value that represents a specific date and time from the current DateTimeOffset object. | .gif) .gif) | Subtract(TimeSpan) | Subtracts a specified time interval from the current DateTimeOffset object. | .gif) | ToFileTime | Converts the value of the current DateTimeOffset object to a Windows file time. | .gif) .gif) | ToLocalTime | Converts the current DateTimeOffset object to a DateTimeOffset object that represents the local time. | .gif) .gif) | ToOffset | Converts the value of the current DateTimeOffset object to the date and time specified by an offset value. | .gif) .gif) | ToString()()() | Converts the value of the current DateTimeOffset object to its equivalent string representation. (Overrides ValueType..::.ToString()()().) | .gif) .gif) | ToString(IFormatProvider) | Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified culture-specific formatting information. | .gif) | ToString(String) | Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified format. | .gif) .gif) | ToString(String, IFormatProvider) | Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified format and culture-specific format information. | .gif) .gif) | ToUniversalTime | Converts the current DateTimeOffset object to a DateTimeOffset value that represents the Coordinated Universal Time (UTC). | .gif) .gif) | TryParse(String, DateTimeOffset%) | Tries to converts a specified string representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded. | .gif) .gif) .gif) | TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset%) | Tries to convert a specified string representation of a date and time to its DateTimeOffset equivalent, and returns a value that indicates whether the conversion succeeded. | .gif) .gif) .gif) | TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset%) | Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. | .gif) .gif) .gif) | TryParseExact(String, array<String>[]()[], IFormatProvider, DateTimeStyles, DateTimeOffset%) | Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match one of the specified formats exactly. | Top

Explicit Interface Implementations

Remarks
The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC). Because it exactly defines a date and time relative to UTC, the DateTimeOffset structure does not include a Kind member, as the DateTime structure does. It represents dates and times with values whose UTC ranges from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era), to 11:59:59 P.M., December 31, 9999 A.D. (C.E.). The time component of a DateTimeOffset value is measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calendar. A DateTimeOffset value is always expressed in the context of an explicit or default calendar. Ticks that are attributable to leap seconds are not included in the total number of ticks. Although a DateTimeOffset value includes an offset, it is not a fully time zone-aware data structure. While an offset from UTC is one characteristic of a time zone, it does not unambiguously identify a time zone. Not only do multiple time zones share the same offset from UTC, but the offset of a single time zone changes if it observes daylight saving time. This means that, as soon as a DateTimeOffset value is disassociated from its time zone, it can no longer be unambiguously linked back to its original time zone. Because DateTimeOffset is a structure, a DateTimeOffset object that has been declared but not otherwise initialized contains the default values for each of its member fields. This means that its DateTime property is set to DateTimeOffset..::.MinValue and its Offset property is set to TimeSpan..::.Zero. You can create a new DateTimeOffset value by calling any of the overloads of its constructor, which are similar to the overloaded constructors for the DateTime structure. You can also create a new DateTimeOffset value by assigning it a DateTime value. This is an implicit conversion; it does not require a casting operator (in C#) or call to a conversion method (in Visual Basic). You can also initialize a DateTimeOffset value from the string representation of a date and time by calling a number of static string parsing methods, which include Parse, ParseExact, TryParse, and TryParseExact. The members of the DateTimeOffset structure provide functionality in the following areas: Date and time arithmetic. You can add or subtract either dates or time intervals from a particular DateTimeOffset value. Arithmetic operations with DateTimeOffset values, unlike those with DateTime values, adjust for differences in time offsets when returning a result. For example, the following code uses DateTime variables to subtract the current local time from the current UTC time. The code then uses DateTimeOffset variables to perform the same operation. The subtraction with DateTime values returns the local time zone's difference from UTC, while the subtraction with DateTimeOffset values returns TimeSpan..::.Zero.
Module DateArithmetic
Public Sub Main()
Dim date1, date2 As Date
Dim dateOffset1, dateOffset2 As DateTimeOffset
Dim difference As TimeSpan
' Find difference between Date.Now and Date.UtcNow
date1 = Date.Now
date2 = Date.UtcNow
difference = date1 - date2
Console.WriteLine("{0} - {1} = {2}", date1, date2, difference)
' Find difference between Now and UtcNow using DateTimeOffset
dateOffset1 = date.Now
dateOffset2 = date.UtcNow
difference = dateOffset1 - dateOffset2
Console.WriteLine("{0} - {1} = {2}", _
dateOffset1, dateOffset2, difference)
' If run in the Pacific Standard time zone on 4/2/2007, the example
' displays the following output to the console:
' 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
' 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00
End Sub
End Module
using System;
public class DateArithmetic
{
public static void Main()
{
DateTime date1, date2;
DateTimeOffset dateOffset1, dateOffset2;
TimeSpan difference;
// Find difference between Date.Now and Date.UtcNow
date1 = DateTime.Now;
date2 = DateTime.UtcNow;
difference = date1 - date2;
Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);
// Find difference between Now and UtcNow using DateTimeOffset
dateOffset1 = DateTimeOffset.Now;
dateOffset2 = DateTimeOffset.UtcNow;
difference = dateOffset1 - dateOffset2;
Console.WriteLine("{0} - {1} = {2}",
dateOffset1, dateOffset2, difference);
// If run in the Pacific Standard time zone on 4/2/2007, the example
// displays the following output to the console:
// 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
// 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00
}
}
Type conversion operations. You can convert DateTimeOffset values to DateTime values and vice versa. Time manipulation and extraction operations. You can extract either the date or the time of a DateTimeOffset value. You can also retrieve the value of a particular DateTimeOffset component, such as its year or its month. Date and time conversion. You can convert any DateTimeOffset value to another DateTimeOffset value that represents the same point in time in another time zone. However, a time zone's adjustment rules are applied only in the case of the ToLocalTime method, which converts a DateTimeOffset value to the date and time in the local system zone. Date and time comparison. You can determine whether any particular DateTimeOffset value is earlier than, the same as, or later than another DateTimeOffset value. Before the comparison is performed, all values are converted to UTC.

Version Information
.NET FrameworkSupported in: 4, 3.5 SP1, 3.0 SP1, 2.0 SP1 .NET Framework Client ProfileSupported in: 4, 3.5 SP1 Portable Class LibrarySupported in: Portable Class Library

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Biblioteca de clases de .NET Framework DateTimeOffset (Estructura) Representa un momento en el tiempo, normalmente expresado como una fecha y hora del día, relativo a la hora universal coordinada (UTC).
Espacio de nombres:
System
Ensamblado:
mscorlib (en mscorlib.dll)

Sintaxis
<SerializableAttribute> _
Public Structure DateTimeOffset _
Implements IComparable, IFormattable, ISerializable, IDeserializationCallback, _
IComparable(Of DateTimeOffset), IEquatable(Of DateTimeOffset)
[SerializableAttribute]
public struct DateTimeOffset : IComparable,
IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>,
IEquatable<DateTimeOffset>
[SerializableAttribute]
public value class DateTimeOffset : IComparable,
IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>,
IEquatable<DateTimeOffset>
[<Sealed>]
[<SerializableAttribute>]
type DateTimeOffset =
struct
interface IComparable
interface IFormattable
interface ISerializable
interface IDeserializationCallback
interface IComparable<DateTimeOffset>
interface IEquatable<DateTimeOffset>
end
El tipo DateTimeOffset expone los siguientes miembros.

Constructores
|
| Nombre | Descripción |
|---|
.gif) .gif) | DateTimeOffset(DateTime) | Inicializa una nueva instancia de la estructura DateTimeOffset utilizando el valor DateTime especificado. | .gif) .gif) | DateTimeOffset(DateTime, TimeSpan) | Inicializa una nueva instancia de la estructura DateTimeOffset utilizando el valor DateTime y el desplazamiento especificados. | .gif) .gif) | DateTimeOffset(Int64, TimeSpan) | Inicializa una nueva instancia de la estructura DateTimeOffset utilizando el número de pasos y el desplazamiento especificados. | .gif) .gif) | DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) | Inicializa una nueva instancia de la estructura DateTimeOffset usando el año, mes, día, hora, minuto, segundo y desplazamiento especificados. | .gif) .gif) | DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, TimeSpan) | Inicializa una nueva instancia de la estructura DateTimeOffset usando el año, mes, día, hora, minuto, segundo, milisegundo y desplazamiento especificados. | .gif) .gif) | DateTimeOffset(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, TimeSpan) | Inicializa una nueva instancia de la estructura DateTimeOffset usando el año, mes, día, hora, minuto, segundo y milisegundo especificados de un calendario indicado. | Arriba

Métodos
|
| Nombre | Descripción |
|---|
.gif) .gif) | Add | Agrega un intervalo de tiempo especificado a un objeto DateTimeOffset. | .gif) .gif) | AddDays | Suma un número especificado de días completos y fraccionarios al objeto DateTimeOffset actual. | .gif) .gif) | AddHours | Suma un número especificado de horas completas y fraccionarias al objeto DateTimeOffset actual. | .gif) .gif) | AddMilliseconds | Agrega un número de milisegundos especificado al objeto DateTimeOffset actual. | .gif) .gif) | AddMinutes | Suma un número especificado de minutos completos y fraccionarios al objeto DateTimeOffset actual. | .gif) .gif) | AddMonths | Agrega un número de meses especificado al objeto DateTimeOffset actual. | .gif) .gif) | AddSeconds | Suma un número especificado de segundos completos y fraccionarios al objeto DateTimeOffset actual. | .gif) .gif) | AddTicks | Agrega un número de pasos especificado al objeto DateTimeOffset actual. | .gif) .gif) | AddYears | Suma un número especificado de años al objeto DateTimeOffset. | .gif) .gif) .gif) | Compare | Compara dos objetos DateTimeOffset e indica si el primero es anterior, igual o posterior al segundo. | .gif) .gif) | CompareTo | Compara el objeto DateTimeOffset actual con un objeto DateTimeOffset especificado e indica si el objeto actual es anterior, igual o posterior al segundo objeto DateTimeOffset. | .gif) .gif) | Equals(DateTimeOffset) | Determina si el objeto DateTimeOffset actual representa el mismo momento en el tiempo que el objeto DateTimeOffset especificado. | .gif) .gif) | Equals(Object) | Determina si un objeto DateTimeOffset representa el mismo momento en el tiempo que un objeto especificado. (Invalida a ValueType..::.Equals(Object)). | .gif) .gif) .gif) | Equals(DateTimeOffset, DateTimeOffset) | Determina si dos objetos DateTimeOffset especificados representan el mismo momento en el tiempo. | .gif) .gif) | EqualsExact | Determina si el objeto DateTimeOffset actual representa la misma hora y tiene el mismo desplazamiento que un objeto DateTimeOffset especificado. | .gif) .gif) | Finalize | Permite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados. (Se hereda de Object). | .gif) .gif) | FromFileTime | Convierte la hora de archivo de Windows especificada en una hora local equivalente. | .gif) .gif) | GetHashCode | Devuelve el código hash del objeto DateTimeOffset actual. (Invalida a ValueType..::.GetHashCode()()()). | .gif) .gif) | GetType | Obtiene el objeto Type de la instancia actual. (Se hereda de Object). | .gif) .gif) | MemberwiseClone | Crea una copia superficial del objeto Object actual. (Se hereda de Object). | .gif) .gif) | Parse(String) | Convierte la representación de cadena especificada de una fecha, hora y desplazamiento en su equivalente de DateTimeOffset. | .gif) .gif) .gif) | Parse(String, IFormatProvider) | Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTimeOffset equivalente, utilizando la información de formato específica de la referencia cultural especificada. | .gif) .gif) .gif) | Parse(String, IFormatProvider, DateTimeStyles) | Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTimeOffset equivalente, utilizando la información de formato específica de la referencia cultural y el estilo de formato especificados. | .gif) .gif) .gif) | ParseExact(String, String, IFormatProvider) | Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTimeOffset equivalente, utilizando la información de formato específica de la referencia cultural y el formato especificados. El formato de la representación de cadena debe coincidir exactamente con el formato especificado. | .gif) .gif) .gif) | ParseExact(String, String, IFormatProvider, DateTimeStyles) | Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTimeOffset equivalente, utilizando el formato, la información de formato específica de la referencia cultural y el estilo especificados. El formato de la representación de cadena debe coincidir exactamente con el formato especificado. | .gif) .gif) .gif) | ParseExact(String, array<String>[]()[], IFormatProvider, DateTimeStyles) | Convierte la representación de cadena especificada para una fecha y hora en su equivalente de DateTimeOffset, usando los formatos, la información de formato específica de la referencia cultural y el estilo especificados. El formato de la representación de cadena debe coincidir exactamente con uno de los formatos especificados. | .gif) .gif) | Subtract(DateTimeOffset) | Resta un valor DateTimeOffset que representa una fecha y hora concreta del objeto DateTimeOffset actual. | .gif) .gif) | Subtract(TimeSpan) | Resta un intervalo de tiempo especificado del objeto DateTimeOffset actual. | .gif) | ToFileTime | Convierte el valor del objeto DateTimeOffset actual en una hora de archivo de Windows. | .gif) .gif) | ToLocalTime | Convierte el objeto DateTimeOffset actual con un objeto DateTimeOffset que representa la hora local. | .gif) .gif) | ToOffset | Convierte el valor del objeto DateTimeOffset actual en la fecha y hora especificadas por un valor de desplazamiento. | .gif) .gif) | ToString()()() | Convierte el valor del objeto DateTimeOffset actual en su representación de cadena equivalente. (Invalida a ValueType..::.ToString()()()). | .gif) .gif) | ToString(IFormatProvider) | Convierte el valor del objeto DateTimeOffset actual en su representación de cadena equivalente usando la información de formato específica de la referencia cultural especificada. | .gif) | ToString(String) | Convierte el valor del objeto DateTimeOffset actual en su representación de cadena equivalente utilizando el formato especificado. | .gif) .gif) | ToString(String, IFormatProvider) | Convierte el valor del objeto DateTimeOffset actual en su representación de cadena equivalente utilizando el formato y la información de formato específica de la referencia cultural especificados. | .gif) .gif) | ToUniversalTime | Convierte el objeto DateTimeOffset actual en un valor DateTimeOffset que representa la hora universal coordinada (UCT). | .gif) .gif) | TryParse(String, DateTimeOffset%) | Intenta convertir una representación de cadena especificada de una fecha y hora en su DateTimeOffset equivalente y devuelve un valor que indica si la conversión tuvo éxito. | .gif) .gif) .gif) | TryParse(String, IFormatProvider, DateTimeStyles, DateTimeOffset%) | Intenta convertir una representación de cadena especificada de una fecha y hora en su DateTimeOffset equivalente y devuelve un valor que indica si la conversión tuvo éxito. | .gif) .gif) .gif) | TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTimeOffset%) | Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTimeOffset equivalente, utilizando el formato, la información de formato específica de la referencia cultural y el estilo especificados. El formato de la representación de cadena debe coincidir exactamente con el formato especificado. | .gif) .gif) .gif) | TryParseExact(String, array<String>[]()[], IFormatProvider, DateTimeStyles, DateTimeOffset%) | Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTimeOffset equivalente, utilizando la matriz de formatos, la información de formato específica de la referencia cultural y el estilo especificados. El formato de la representación de cadena debe coincidir exactamente con uno de los formatos especificados. | Arriba

Implementaciones explícitas de interfaces

Comentarios
La estructura DateTimeOffset incluye un valor DateTime, junto con una propiedad Offset que define la diferencia entre la fecha y hora de la instancia actual de DateTimeOffset y la hora universal coordinada (UTC). Dado que define exactamente una fecha y hora con respecto a la hora UTC, la estructura DateTimeOffset no incluye un miembro Kind, a diferencia de la estructura DateTime. Representa las fechas y horas con valores cuya hora UTC va de las 00:00:00 de la media noche del 1 de enero de 0001 d.C., a las 11:59:59 p.m. del 31 de diciembre de 9999 d.C. (Era cristiana). El componente de hora de un valor DateTimeOffset se mide en unidades de 100 nanosegundos denominadas pasos, y una fecha concreta es el número de pasos transcurridos desde la medianoche (00:00) del 1 de enero de 0001 d.C. (C.E.) en el calendario GregorianCalendar. Un valor DateTimeOffset siempre se expresa en el contexto de un calendario explícito o predeterminado. Los pasos que son atribuibles a los segundos intercalados no se incluyen en el número de pasos total. Aunque un valor DateTimeOffset incluye un desplazamiento, no es una estructura de datos totalmente orientada a la zona horaria. Aunque un desplazamiento de hora UTC es una característica de una zona horaria, no identifica inequívocamente una zona horaria. No sólo varias zonas horarias comparten el mismo desplazamiento de hora UTC, además el desplazamiento de una misma zona horaria cambia si utiliza el horario de verano. Esto significa que, en cuanto un valor DateTimeOffset se desasocia de su zona horaria, ya no puede volver a vincularse inequívocamente a su zona horaria original. Como DateTimeOffset es una estructura, un objeto DateTimeOffset que se ha declarado pero no se ha inicializado contiene valores predeterminados para cada uno de sus campos miembro. Esto significa que su propiedad DateTime se establece en DateTimeOffset..::.MinValue y su propiedad Offset se establece en TimeSpan..::.Zero. Puede crear un nuevo valor DateTimeOffset llamando a cualquiera de las sobrecargas de su constructor, que son similares a los constructores sobrecargados para la estructura DateTime. También puede crear un nuevo valor DateTimeOffset asignándole un valor DateTime. Ésta es una conversión implícita; no requiere un operador de conversión (en C#) ni llamar a un método de conversión (en Visual Basic). También puede inicializar un valor DateTimeOffset a partir de la representación de cadena de una fecha y hora llamando a varios métodos de análisis de cadenas estáticas, entre los que se incluyen Parse, ParseExact, TryParse y TryParseExact. Los miembros de la estructura DateTimeOffset proporcionan funcionalidad en las áreas siguientes: Aritmética de fecha y hora. Puede sumar o restar intervalos de fecha u hora de un valor DateTimeOffset determinado. En las operaciones aritmética con valores DateTimeOffset, a diferencia de aquéllas con valores DateTime, se ajustan para las diferencias en los desplazamientos de hora al devolver un resultado. Por ejemplo, en el código siguiente se usan variables DateTime para restar la hora local actual de la hora UTC actual. A continuación, en el código se usan variables DateTimeOffset para realizar la misma operación. La resta con valores DateTime devuelve la diferencia entre la zona horaria local y la hora UTC, mientras la resta con valores DateTimeOffset devuelve TimeSpan..::.Zero.
Module DateArithmetic
Public Sub Main()
Dim date1, date2 As Date
Dim dateOffset1, dateOffset2 As DateTimeOffset
Dim difference As TimeSpan
' Find difference between Date.Now and Date.UtcNow
date1 = Date.Now
date2 = Date.UtcNow
difference = date1 - date2
Console.WriteLine("{0} - {1} = {2}", date1, date2, difference)
' Find difference between Now and UtcNow using DateTimeOffset
dateOffset1 = date.Now
dateOffset2 = date.UtcNow
difference = dateOffset1 - dateOffset2
Console.WriteLine("{0} - {1} = {2}", _
dateOffset1, dateOffset2, difference)
' If run in the Pacific Standard time zone on 4/2/2007, the example
' displays the following output to the console:
' 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
' 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00
End Sub
End Module
using System;
public class DateArithmetic
{
public static void Main()
{
DateTime date1, date2;
DateTimeOffset dateOffset1, dateOffset2;
TimeSpan difference;
// Find difference between Date.Now and Date.UtcNow
date1 = DateTime.Now;
date2 = DateTime.UtcNow;
difference = date1 - date2;
Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);
// Find difference between Now and UtcNow using DateTimeOffset
dateOffset1 = DateTimeOffset.Now;
dateOffset2 = DateTimeOffset.UtcNow;
difference = dateOffset1 - dateOffset2;
Console.WriteLine("{0} - {1} = {2}",
dateOffset1, dateOffset2, difference);
// If run in the Pacific Standard time zone on 4/2/2007, the example
// displays the following output to the console:
// 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
// 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00
}
}
Operaciones de conversión de tipos. Los valores DateTimeOffset pueden convertirse en valores DateTime y viceversa. Operaciones de extracción y manipulación de la hora. Puede extraerse la fecha o la hora de un valor DateTimeOffset. También puede recuperarse el valor de un componente DateTimeOffset determinado, como el año o el mes. Conversión de fecha y hora. Cualquier valor DateTimeOffset puede convertirse en otro valor DateTimeOffset que representa el mismo momento en el tiempo en otra zona horaria. Sin embargo, las reglas de ajuste de una zona horaria sólo se aplican en el caso del método ToLocalTime, que convierte un valor DateTimeOffset en la fecha y hora de la zona del sistema local. Comparación de fecha y hora. Puede determinarse si cualquier valor DateTimeOffset determinado es anterior, igual o posterior a otro valor DateTimeOffset. Antes de realizar la comparación, todos los valores se convierten a la hora UTC.

Información de versión
.NET FrameworkCompatible con: 4, 3.5 SP1, 3.0 SP1, 2.0 SP1 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1 Compatible con:

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Seguridad para subprocesos
Todos los miembros static ( Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Vea también
|