Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.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)
Visual Basic
<SerializableAttribute> _
Public Structure DateTimeOffset _
    Implements IComparable, IFormattable, ISerializable, IDeserializationCallback,  _
    IComparable(Of DateTimeOffset), IEquatable(Of DateTimeOffset)
C#
[SerializableAttribute]
public struct DateTimeOffset : IComparable, 
    IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>, 
    IEquatable<DateTimeOffset>
Visual C++
[SerializableAttribute]
public value class DateTimeOffset : IComparable, 
    IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>, 
    IEquatable<DateTimeOffset>
F#
[<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.

  NameDescription
Public methodSupported by Portable Class LibraryDateTimeOffset(DateTime)Initializes a new instance of the DateTimeOffset structure using the specified DateTime value.
Public methodSupported by Portable Class LibraryDateTimeOffset(DateTime, TimeSpan)Initializes a new instance of the DateTimeOffset structure using the specified DateTime value and offset.
Public methodSupported by Portable Class LibraryDateTimeOffset(Int64, TimeSpan)Initializes a new instance of the DateTimeOffset structure using the specified number of ticks and offset.
Public methodSupported by Portable Class LibraryDateTimeOffset(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.
Public methodSupported by Portable Class LibraryDateTimeOffset(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.
Public methodSupported by Portable Class LibraryDateTimeOffset(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
  NameDescription
Public propertySupported by Portable Class LibraryDateGets a DateTime value that represents the date component of the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryDateTimeGets a DateTime value that represents the date and time of the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryDayGets the day of the month represented by the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryDayOfWeekGets the day of the week represented by the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryDayOfYearGets the day of the year represented by the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryHourGets the hour component of the time represented by the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryLocalDateTimeGets a DateTime value that represents the local date and time of the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryMillisecondGets the millisecond component of the time represented by the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryMinuteGets the minute component of the time represented by the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryMonthGets the month component of the date represented by the current DateTimeOffset object.
Public propertyStatic memberSupported by Portable Class LibraryNowGets a DateTimeOffset object that is set to the current date and time on the current computer, with the offset set to the local time's offset from Coordinated Universal Time (UTC).
Public propertySupported by Portable Class LibraryOffsetGets the time's offset from Coordinated Universal Time (UTC).
Public propertySupported by Portable Class LibrarySecondGets the second component of the clock time represented by the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryTicksGets the number of ticks that represents the date and time of the current DateTimeOffset object in clock time.
Public propertySupported by Portable Class LibraryTimeOfDayGets the time of day for the current DateTimeOffset object.
Public propertySupported by Portable Class LibraryUtcDateTimeGets a DateTime value that represents the Coordinated Universal Time (UTC) date and time of the current DateTimeOffset object.
Public propertyStatic memberSupported by Portable Class LibraryUtcNowGets a DateTimeOffset object whose date and time are set to the current Coordinated Universal Time (UTC) date and time and whose offset is TimeSpan..::.Zero.
Public propertySupported by Portable Class LibraryUtcTicksGets the number of ticks that represents the date and time of the current DateTimeOffset object in Coordinated Universal Time (UTC).
Public propertySupported by Portable Class LibraryYearGets the year component of the date represented by the current DateTimeOffset object.
Top
  NameDescription
Public methodSupported by Portable Class LibraryAddAdds a specified time interval to a DateTimeOffset object.
Public methodSupported by Portable Class LibraryAddDaysAdds a specified number of whole and fractional days to the current DateTimeOffset object.
Public methodSupported by Portable Class LibraryAddHoursAdds a specified number of whole and fractional hours to the current DateTimeOffset object.
Public methodSupported by Portable Class LibraryAddMillisecondsAdds a specified number of milliseconds to the current DateTimeOffset object.
Public methodSupported by Portable Class LibraryAddMinutesAdds a specified number of whole and fractional minutes to the current DateTimeOffset object.
Public methodSupported by Portable Class LibraryAddMonthsAdds a specified number of months to the current DateTimeOffset object.
Public methodSupported by Portable Class LibraryAddSecondsAdds a specified number of whole and fractional seconds to the current DateTimeOffset object.
Public methodSupported by Portable Class LibraryAddTicksAdds a specified number of ticks to the current DateTimeOffset object.
Public methodSupported by Portable Class LibraryAddYearsAdds a specified number of years to the DateTimeOffset object.
Public methodStatic memberSupported by Portable Class LibraryCompareCompares two DateTimeOffset objects and indicates whether the first is earlier than the second, equal to the second, or later than the second.
Public methodSupported by Portable Class LibraryCompareToCompares 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.
Public methodSupported by Portable Class LibraryEquals(DateTimeOffset)Determines whether the current DateTimeOffset object represents the same point in time as a specified DateTimeOffset object.
Public methodSupported by Portable Class LibraryEquals(Object)Determines whether a DateTimeOffset object represents the same point in time as a specified object. (Overrides ValueType..::.Equals(Object).)
Public methodStatic memberSupported by Portable Class LibraryEquals(DateTimeOffset, DateTimeOffset)Determines whether two specified DateTimeOffset objects represent the same point in time.
Public methodSupported by Portable Class LibraryEqualsExactDetermines whether the current DateTimeOffset object represents the same time and has the same offset as a specified DateTimeOffset object.
Protected methodSupported by Portable Class LibraryFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodStatic memberFromFileTimeConverts the specified Windows file time to an equivalent local time.
Public methodSupported by Portable Class LibraryGetHashCodeReturns the hash code for the current DateTimeOffset object. (Overrides ValueType..::.GetHashCode()()().)
Public methodSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Portable Class LibraryMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodStatic memberParse(String)Converts the specified string representation of a date, time, and offset to its DateTimeOffset equivalent.
Public methodStatic memberSupported by Portable Class LibraryParse(String, IFormatProvider)Converts the specified string representation of a date and time to its DateTimeOffset equivalent using the specified culture-specific format information.
Public methodStatic memberSupported by Portable Class LibraryParse(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.
Public methodStatic memberSupported by Portable Class LibraryParseExact(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.
Public methodStatic memberSupported by Portable Class LibraryParseExact(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.
Public methodStatic memberSupported by Portable Class LibraryParseExact(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.
Public methodSupported by Portable Class LibrarySubtract(DateTimeOffset)Subtracts a DateTimeOffset value that represents a specific date and time from the current DateTimeOffset object.
Public methodSupported by Portable Class LibrarySubtract(TimeSpan)Subtracts a specified time interval from the current DateTimeOffset object.
Public methodToFileTimeConverts the value of the current DateTimeOffset object to a Windows file time.
Public methodSupported by Portable Class LibraryToLocalTimeConverts the current DateTimeOffset object to a DateTimeOffset object that represents the local time.
Public methodSupported by Portable Class LibraryToOffsetConverts the value of the current DateTimeOffset object to the date and time specified by an offset value.
Public methodSupported by Portable Class LibraryToString()()()Converts the value of the current DateTimeOffset object to its equivalent string representation. (Overrides ValueType..::.ToString()()().)
Public methodSupported by Portable Class LibraryToString(IFormatProvider)Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified culture-specific formatting information.
Public methodToString(String)Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified format.
Public methodSupported by Portable Class LibraryToString(String, IFormatProvider)Converts the value of the current DateTimeOffset object to its equivalent string representation using the specified format and culture-specific format information.
Public methodSupported by Portable Class LibraryToUniversalTimeConverts the current DateTimeOffset object to a DateTimeOffset value that represents the Coordinated Universal Time (UTC).
Public methodStatic memberTryParse(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.
Public methodStatic memberSupported by Portable Class LibraryTryParse(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.
Public methodStatic memberSupported by Portable Class LibraryTryParseExact(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.
Public methodStatic memberSupported by Portable Class LibraryTryParseExact(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
  NameDescription
Public operatorStatic memberSupported by Portable Class LibraryAdditionAdds a specified time interval to a DateTimeOffset object that has a specified date and time, and yields a DateTimeOffset object that has new a date and time.
Public operatorStatic memberSupported by Portable Class LibraryEqualityDetermines whether two specified DateTimeOffset objects represent the same point in time.
Public operatorStatic memberSupported by Portable Class LibraryGreaterThanDetermines whether one specified DateTimeOffset object is greater than (or later than) a second specified DateTimeOffset object.
Public operatorStatic memberSupported by Portable Class LibraryGreaterThanOrEqualDetermines whether one specified DateTimeOffset object is greater than or equal to a second specified DateTimeOffset object.
Public operatorStatic memberSupported by Portable Class LibraryImplicitWideningImplicitImplicit(DateTime to DateTimeOffset)Defines an implicit conversion of a DateTime object to a DateTimeOffset object.
Public operatorStatic memberSupported by Portable Class LibraryInequalityDetermines whether two specified DateTimeOffset objects refer to different points in time.
Public operatorStatic memberSupported by Portable Class LibraryLessThanDetermines whether one specified DateTimeOffset object is less than a second specified DateTimeOffset object.
Public operatorStatic memberSupported by Portable Class LibraryLessThanOrEqualDetermines whether one specified DateTimeOffset object is less than a second specified DateTimeOffset object.
Public operatorStatic memberSupported by Portable Class LibrarySubtraction(DateTimeOffset, DateTimeOffset)Subtracts one DateTimeOffset object from another and yields a time interval.
Public operatorStatic memberSupported by Portable Class LibrarySubtraction(DateTimeOffset, TimeSpan)Subtracts a specified time interval from a specified date and time, and yields a new date and time.
Top
  NameDescription
Public fieldStatic memberSupported by Portable Class LibraryMaxValueRepresents the greatest possible value of DateTimeOffset. This field is read-only.
Public fieldStatic memberSupported by Portable Class LibraryMinValueRepresents the earliest possible DateTimeOffset value. This field is read-only.
Top
  NameDescription
Explicit interface implemetationPrivate methodIComparable..::.CompareToInfrastructure. Compares the value of the current DateTimeOffset object with another object of the same type.
Explicit interface implemetationPrivate methodIDeserializationCallback..::.OnDeserializationInfrastructure. Runs when the deserialization of an object has been completed.
Explicit interface implemetationPrivate methodISerializable..::.GetObjectDataInfrastructure. Populates a SerializationInfo object with the data required to serialize the current DateTimeOffset object.
Top

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.

NoteNote

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. For example, to add the number of seconds represented by a specified number of ticks to the Second component of a DateTimeOffset value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.

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.

    Visual Basic
    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
    
    C#
    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.

.NET Framework

Supported in: 4, 3.5 SP1, 3.0 SP1, 2.0 SP1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

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.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
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)
Visual Basic
<SerializableAttribute> _
Public Structure DateTimeOffset _
    Implements IComparable, IFormattable, ISerializable, IDeserializationCallback,  _
    IComparable(Of DateTimeOffset), IEquatable(Of DateTimeOffset)
C#
[SerializableAttribute]
public struct DateTimeOffset : IComparable, 
    IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>, 
    IEquatable<DateTimeOffset>
Visual C++
[SerializableAttribute]
public value class DateTimeOffset : IComparable, 
    IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>, 
    IEquatable<DateTimeOffset>
F#
[<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.

  NombreDescripción
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifDateTimeOffset(DateTime)Inicializa una nueva instancia de la estructura DateTimeOffset utilizando el valor DateTime especificado.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifDateTimeOffset(DateTime, TimeSpan)Inicializa una nueva instancia de la estructura DateTimeOffset utilizando el valor DateTime y el desplazamiento especificados.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifDateTimeOffset(Int64, TimeSpan)Inicializa una nueva instancia de la estructura DateTimeOffset utilizando el número de pasos y el desplazamiento especificados.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifDateTimeOffset(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.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifDateTimeOffset(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.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifDateTimeOffset(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
  NombreDescripción
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifDateObtiene un valor DateTime que representa el componente de fecha del objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifDateTimeObtiene un valor DateTime que representa la fecha y hora del objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifDayObtiene el día del mes representado por el objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifDayOfWeekObtiene el día de la semana representado por el objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifDayOfYearObtiene el día del año representado por el objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifHourObtiene el componente de hora de la hora representada por el objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifLocalDateTimeObtiene un valor DateTime que representa la fecha y hora local del objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifMillisecondObtiene el componente de milisegundos de la hora representada por el objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifMinuteObtiene el componente de minuto de la hora representada por el objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifMonthObtiene el componente de mes de la fecha representada por el objeto DateTimeOffset actual.
Propiedad públicaMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifNowObtiene un objeto DateTimeOffset que se establece en la fecha y hora actual del equipo actual, con el desplazamiento establecido como desplazamiento de la hora local respecto de la hora universal coordinada (UTC).
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifOffsetObtiene el desplazamiento de la hora respecto de la hora universal coordinada (UTC).
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifSecondObtiene el componente de milisegundos de la hora representada por el objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifTicksObtiene el número de pasos que representa la fecha y hora del objeto DateTimeOffset actual en la hora.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifTimeOfDayObtiene la hora del día del objeto DateTimeOffset actual.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifUtcDateTimeObtiene un valor DateTime que representa la fecha y hora de la hora universal coordinada (UTC) del objeto DateTimeOffset actual.
Propiedad públicaMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifUtcNowObtiene un objeto DateTimeOffset cuya fecha y hora está establecida en la fecha y hora actual de la hora universal coordinada (UTC) y cuyo desplazamiento es TimeSpan..::.Zero.
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifUtcTicksObtiene el número de pasos que representan la fecha y hora del objeto DateTimeOffset en la hora universal coordinada (UTC).
Propiedad públicaBb341783.PortableClassLibrary(es-es,VS.100).gifYearObtiene el componente de año de la fecha representada por el objeto DateTimeOffset actual.
Arriba
  NombreDescripción
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddAgrega un intervalo de tiempo especificado a un objeto DateTimeOffset.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddDaysSuma un número especificado de días completos y fraccionarios al objeto DateTimeOffset actual.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddHoursSuma un número especificado de horas completas y fraccionarias al objeto DateTimeOffset actual.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddMillisecondsAgrega un número de milisegundos especificado al objeto DateTimeOffset actual.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddMinutesSuma un número especificado de minutos completos y fraccionarios al objeto DateTimeOffset actual.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddMonthsAgrega un número de meses especificado al objeto DateTimeOffset actual.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddSecondsSuma un número especificado de segundos completos y fraccionarios al objeto DateTimeOffset actual.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddTicksAgrega un número de pasos especificado al objeto DateTimeOffset actual.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifAddYearsSuma un número especificado de años al objeto DateTimeOffset.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifCompareCompara dos objetos DateTimeOffset e indica si el primero es anterior, igual o posterior al segundo.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifCompareToCompara el objeto DateTimeOffset actual con un objeto DateTimeOffset especificado e indica si el objeto actual es anterior, igual o posterior al segundo objeto DateTimeOffset.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifEquals(DateTimeOffset)Determina si el objeto DateTimeOffset actual representa el mismo momento en el tiempo que el objeto DateTimeOffset especificado.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifEquals(Object)Determina si un objeto DateTimeOffset representa el mismo momento en el tiempo que un objeto especificado. (Invalida a ValueType..::.Equals(Object)).
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifEquals(DateTimeOffset, DateTimeOffset)Determina si dos objetos DateTimeOffset especificados representan el mismo momento en el tiempo.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifEqualsExactDetermina si el objeto DateTimeOffset actual representa la misma hora y tiene el mismo desplazamiento que un objeto DateTimeOffset especificado.
Método protegidoBb341783.PortableClassLibrary(es-es,VS.100).gifFinalizePermite 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).
Método públicoMiembro estáticoFromFileTimeConvierte la hora de archivo de Windows especificada en una hora local equivalente.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifGetHashCodeDevuelve el código hash del objeto DateTimeOffset actual. (Invalida a ValueType..::.GetHashCode()()()).
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método protegidoBb341783.PortableClassLibrary(es-es,VS.100).gifMemberwiseCloneCrea una copia superficial del objeto Object actual. (Se hereda de Object).
Método públicoMiembro estáticoParse(String)Convierte la representación de cadena especificada de una fecha, hora y desplazamiento en su equivalente de DateTimeOffset.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifParse(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.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifParse(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.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifParseExact(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.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifParseExact(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.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifParseExact(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.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifSubtract(DateTimeOffset)Resta un valor DateTimeOffset que representa una fecha y hora concreta del objeto DateTimeOffset actual.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifSubtract(TimeSpan)Resta un intervalo de tiempo especificado del objeto DateTimeOffset actual.
Método públicoToFileTimeConvierte el valor del objeto DateTimeOffset actual en una hora de archivo de Windows.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifToLocalTimeConvierte el objeto DateTimeOffset actual con un objeto DateTimeOffset que representa la hora local.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifToOffsetConvierte el valor del objeto DateTimeOffset actual en la fecha y hora especificadas por un valor de desplazamiento.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifToString()()()Convierte el valor del objeto DateTimeOffset actual en su representación de cadena equivalente. (Invalida a ValueType..::.ToString()()()).
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifToString(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.
Método públicoToString(String)Convierte el valor del objeto DateTimeOffset actual en su representación de cadena equivalente utilizando el formato especificado.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifToString(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.
Método públicoBb341783.PortableClassLibrary(es-es,VS.100).gifToUniversalTimeConvierte el objeto DateTimeOffset actual en un valor DateTimeOffset que representa la hora universal coordinada (UCT).
Método públicoMiembro estáticoTryParse(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.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifTryParse(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.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifTryParseExact(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.
Método públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifTryParseExact(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
  NombreDescripción
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifAdditionAgrega un intervalo de tiempo especificado a un objeto DateTimeOffset que tiene una fecha y hora especificadas y produce un objeto DateTimeOffset que tiene una fecha y hora nuevas.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifEqualityDetermina si dos objetos DateTimeOffset especificados representan el mismo momento en el tiempo.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifGreaterThanDetermina si un objeto DateTimeOffset especificado es mayor que (o posterior a) el segundo objeto DateTimeOffset especificado.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifGreaterThanOrEqualDetermina si un objeto DateTimeOffset especificado es mayor o igual que un segundo objeto DateTimeOffset especificado.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifImplicitWideningImplicitImplicit(DateTime to DateTimeOffset)Define una conversión implícita de un objeto DateTime en un objeto DateTimeOffset.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifInequalityDetermina si dos objetos DateTimeOffset especificados hacen referencia a diferentes momentos en el tiempo.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifLessThanDetermina si un objeto DateTimeOffset especificado es menor que un segundo objeto DateTimeOffset especificado.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifLessThanOrEqualDetermina si un objeto DateTimeOffset especificado es menor que un segundo objeto DateTimeOffset especificado.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifSubtraction(DateTimeOffset, DateTimeOffset)Resta un objeto DateTimeOffset de otro y produce un intervalo de tiempo.
Operador públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifSubtraction(DateTimeOffset, TimeSpan)Resta un intervalo de tiempo especificado de una fecha y hora especificadas y produce una fecha y hora nuevas.
Arriba
  NombreDescripción
Campo públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifMaxValueRepresenta el mayor valor posible de DateTimeOffset. Este campo es de sólo lectura.
Campo públicoMiembro estáticoBb341783.PortableClassLibrary(es-es,VS.100).gifMinValueRepresenta el menor valor posible de DateTimeOffset. Este campo es de sólo lectura.
Arriba
  NombreDescripción
Implementación explícita de interfacesMétodo privadoIComparable..::.CompareToInfraestructura. Compara el valor del objeto DateTimeOffset actual con otro objeto del mismo tipo.
Implementación explícita de interfacesMétodo privadoIDeserializationCallback..::.OnDeserializationInfraestructura. Se ejecuta cuando se ha completado la deserialización de un objeto.
Implementación explícita de interfacesMétodo privadoISerializable..::.GetObjectDataInfraestructura. Rellena un objeto SerializationInfo con los datos necesarios para serializar el objeto DateTimeOffset actual.
Arriba

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.

NotaNota

Si está trabajando con un valor de pasos que desea convertir en algún otro intervalo de hora, como minutos o segundos, debería utilizar las constantes TimeSpan..::.TicksPerDay, TimeSpan..::.TicksPerHour, TimeSpan..::.TicksPerMinute, TimeSpan..::.TicksPerSecond o TimeSpan..::.TicksPerMillisecond para la conversión. Por ejemplo, para sumar el número de segundos representado por un número de pasos especificado al componente Second de un valor DateTimeOffset, puede utilizar la expresión dateValue.Second + nTicks/Timespan.TicksPerSecond.

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.

    Visual Basic
    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
    
    C#
    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.

.NET Framework

Compatible con: 4, 3.5 SP1, 3.0 SP1, 2.0 SP1

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Compatible con:

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.
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.
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker