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
DateTime Structure

Represents an instant in time, typically expressed as a date and time of day.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic
<SerializableAttribute> _
Public Structure DateTime _
    Implements IComparable, IFormattable, IConvertible, ISerializable,  _
    IComparable(Of DateTime), IEquatable(Of DateTime)
C#
[SerializableAttribute]
public struct DateTime : IComparable, IFormattable, 
    IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>
Visual C++
[SerializableAttribute]
public value class DateTime : IComparable, 
    IFormattable, IConvertible, ISerializable, IComparable<DateTime>, 
    IEquatable<DateTime>
F#
[<Sealed>]
[<SerializableAttribute>]
type DateTime =  
    struct
        interface IComparable
        interface IFormattable
        interface IConvertible
        interface ISerializable
        interface IComparable<DateTime>
        interface IEquatable<DateTime>
    end

The DateTime type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int64)Initializes a new instance of the DateTime structure to a specified number of ticks.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int64, DateTimeKind)Initializes a new instance of the DateTime structure to a specified number of ticks and to Coordinated Universal Time (UTC) or local time.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32)Initializes a new instance of the DateTime structure to the specified year, month, and day.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32, Calendar)Initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32, Int32, Int32, Int32)Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)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.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar)Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second for the specified calendar.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32)Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)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.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar)Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond for the specified calendar.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind)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.
Top
  NameDescription
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryDateGets the date component of this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryDayGets the day of the month represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryDayOfWeekGets the day of the week represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryDayOfYearGets the day of the year represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryHourGets the hour component of the date represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryKindGets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryMillisecondGets the milliseconds component of the date represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryMinuteGets the minute component of the date represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryMonthGets the month component of the date represented by this instance.
Public propertyStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryNowGets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySecondGets the seconds component of the date represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryTicksGets the number of ticks that represent the date and time of this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryTimeOfDayGets the time of day for this instance.
Public propertyStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryTodayGets the current date.
Public propertyStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryUtcNowGets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryYearGets the year component of the date represented by this instance.
Top
  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddReturns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddDaysReturns a new DateTime that adds the specified number of days to the value of this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddHoursReturns a new DateTime that adds the specified number of hours to the value of this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddMillisecondsReturns a new DateTime that adds the specified number of milliseconds to the value of this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddMinutesReturns a new DateTime that adds the specified number of minutes to the value of this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddMonthsReturns a new DateTime that adds the specified number of months to the value of this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddSecondsReturns a new DateTime that adds the specified number of seconds to the value of this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddTicksReturns a new DateTime that adds the specified number of ticks to the value of this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryAddYearsReturns a new DateTime that adds the specified number of years to the value of this instance.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCompareCompares 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.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryCompareTo(DateTime)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.
Public methodSupported by the XNA FrameworkCompareTo(Object)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.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryDaysInMonthReturns the number of days in the specified month and year.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryEquals(DateTime)Returns a value indicating whether this instance is equal to the specified DateTime instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryEquals(Object)Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType..::.Equals(Object).)
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryEquals(DateTime, DateTime)Returns a value indicating whether two instances of DateTime are equal.
Protected methodSupported by the XNA FrameworkSupported 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 memberFromBinaryDeserializes a 64-bit binary value and recreates an original serialized DateTime object.
Public methodStatic memberSupported by the XNA FrameworkFromFileTimeConverts the specified Windows file time to an equivalent local time.
Public methodStatic memberSupported by the XNA FrameworkFromFileTimeUtcConverts the specified Windows file time to an equivalent UTC time.
Public methodStatic memberSupported by the XNA FrameworkFromOADateReturns a DateTime equivalent to the specified OLE Automation Date.
Public methodSupported by the XNA FrameworkGetDateTimeFormats()()()Converts the value of this instance to all the string representations supported by the standard date and time format specifiers.
Public methodSupported by the XNA FrameworkGetDateTimeFormats(Char)Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier.
Public methodSupported by the XNA FrameworkGetDateTimeFormats(IFormatProvider)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.
Public methodSupported by the XNA FrameworkGetDateTimeFormats(Char, IFormatProvider)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.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetHashCodeReturns the hash code for this instance. (Overrides ValueType..::.GetHashCode()()().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetTypeCodeReturns the TypeCode for value type DateTime.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryIsDaylightSavingTimeIndicates whether this instance of DateTime is within the daylight saving time range for the current time zone.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryIsLeapYearReturns an indication whether the specified year is a leap year.
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodStatic memberSupported by the XNA FrameworkParse(String)Converts the specified string representation of a date and time to its DateTime equivalent.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryParse(String, IFormatProvider)Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryParse(String, IFormatProvider, DateTimeStyles)Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryParseExact(String, String, IFormatProvider)Converts the specified string representation of a date and time to its DateTime 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 the XNA FrameworkSupported by Portable Class LibraryParseExact(String, String, IFormatProvider, DateTimeStyles)Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly or an exception is thrown.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryParseExact(String, array<String>[]()[], IFormatProvider, DateTimeStyles)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. The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySpecifyKindCreates 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.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySubtract(DateTime)Subtracts the specified date and time from this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySubtract(TimeSpan)Subtracts the specified duration from this instance.
Public methodToBinarySerializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object.
Public methodSupported by the XNA FrameworkToFileTimeConverts the value of the current DateTime object to a Windows file time.
Public methodSupported by the XNA FrameworkToFileTimeUtcConverts the value of the current DateTime object to a Windows file time.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToLocalTimeConverts the value of the current DateTime object to local time.
Public methodSupported by the XNA FrameworkToLongDateStringConverts the value of the current DateTime object to its equivalent long date string representation.
Public methodSupported by the XNA FrameworkToLongTimeStringConverts the value of the current DateTime object to its equivalent long time string representation.
Public methodSupported by the XNA FrameworkToOADateConverts the value of this instance to the equivalent OLE Automation date.
Public methodSupported by the XNA FrameworkToShortDateStringConverts the value of the current DateTime object to its equivalent short date string representation.
Public methodSupported by the XNA FrameworkToShortTimeStringConverts the value of the current DateTime object to its equivalent short time string representation.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToString()()()Converts the value of the current DateTime object to its equivalent string representation. (Overrides ValueType..::.ToString()()().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToString(IFormatProvider)Converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information.
Public methodSupported by the XNA FrameworkToString(String)Converts the value of the current DateTime object to its equivalent string representation using the specified format.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToString(String, IFormatProvider)Converts the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToUniversalTimeConverts the value of the current DateTime object to Coordinated Universal Time (UTC).
Public methodStatic memberTryParse(String, DateTime%)Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
Public methodStatic memberSupported by Portable Class LibraryTryParse(String, IFormatProvider, DateTimeStyles, DateTime%)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.
Public methodStatic memberSupported by Portable Class LibraryTryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime%)Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. The method returns a value that indicates whether the conversion succeeded.
Public methodStatic memberSupported by Portable Class LibraryTryParseExact(String, array<String>[]()[], IFormatProvider, DateTimeStyles, DateTime%)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. The format of the string representation must match at least one of the specified formats exactly. The method returns a value that indicates whether the conversion succeeded.
Top
  NameDescription
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryAdditionAdds a specified time interval to a specified date and time, yielding a new date and time.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryEqualityDetermines whether two specified instances of DateTime are equal.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryGreaterThanDetermines whether one specified DateTime is greater than another specified DateTime.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryGreaterThanOrEqualDetermines whether one specified DateTime is greater than or equal to another specified DateTime.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryInequalityDetermines whether two specified instances of DateTime are not equal.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryLessThanDetermines whether one specified DateTime is less than another specified DateTime.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryLessThanOrEqualDetermines whether one specified DateTime is less than or equal to another specified DateTime.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySubtraction(DateTime, DateTime)Subtracts a specified date and time from another specified date and time and returns a time interval.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySubtraction(DateTime, TimeSpan)Subtracts a specified time interval from a specified date and time and returns a new date and time.
Top
  NameDescription
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryMaxValueRepresents the largest possible value of DateTime. This field is read-only.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryMinValueRepresents the smallest possible value of DateTime. This field is read-only.
Top
  NameDescription
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToBooleanInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToByteInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToCharInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToDateTimeInfrastructure. Returns the current DateTime object.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToDecimalInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToDoubleInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToInt16Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToInt32Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToInt64Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToSByteInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToSingleInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToTypeInfrastructure. Converts the current DateTime object to an object of a specified type.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToUInt16Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToUInt32Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible..::.ToUInt64Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodISerializable..::.GetObjectDataPopulates a SerializationInfo object with the data needed to serialize the current DateTime object.
Top

The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.).

Time values are 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 (excluding ticks that would be added by leap seconds). For example, a ticks value of 31241376000000000L represents the date, Friday, January 01, 0100 12:00:00 midnight. A DateTime value is always expressed in the context of an explicit or default calendar.

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 DateTime value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.

Instantiating a DateTime Object

You can create a new DateTime value in any of the following ways:

  • By calling any of the overloads of the DateTime constructor that allow you to specify specific elements of the date and time value (such as the year, month, and day, or the number of ticks). The following statement illustrates a call to one of the DateTime constructors to create a date with a specific year, month, day, hour, minute, and second.

    Visual Basic
    Dim date1 As New Date(2008, 5, 1, 8, 30, 52)
    
    C#
    DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
    
  • By using any compiler-specific syntax for declaring date and time values. For example, the following Visual Basic statement initializes a new DateTime value.

    Visual Basic
    Dim date1 As Date = #5/1/2008 8:30:52AM#
    
  • By assigning the DateTime object a date and time value returned by a property or method. 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.

    Visual Basic
    Dim date1 As Date = Date.Now
    Dim date2 As Date = Date.UtcNow
    Dim date3 As Date = Date.Today
    
    C#
    DateTime date1 = DateTime.Now;
    DateTime date2 = DateTime.UtcNow;
    DateTime date3 = DateTime.Today;
    
  • By parsing the string representation of a date and time value. The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. The following example uses the Parse method to parse a string and convert it to a DateTime value.

    Visual Basic
    Dim dateString As String = "5/1/2008 8:30:52 AM"
    Dim date1 As Date = Date.Parse(dateString, _
                             System.Globalization.CultureInfo.InvariantCulture) 
    
    C#
    string dateString = "5/1/2008 8:30:52 AM";
    DateTime date1 = DateTime.Parse(dateString, 
                              System.Globalization.CultureInfo.InvariantCulture); 
    

    Note that the TryParse and TryParseExact methods indicate whether a particular string contains a valid representation of a DateTime value in addition to performing the conversion.

  • By calling the DateTime structure's implicit default constructor. (For details on the implicit default constructor of a value type, see Value Types (C# Reference).) An approximate equivalent, for compilers that support it, is declaring a DateTime value without explicitly assigning a date and time to it. The following example illustrates a call to the DateTime implicit default constructor in C# and Visual Basic, as well as a DateTime variable declaration with no assignment in Visual Basic.

    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))
    
    C#
    DateTime 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));
    

DateTime Values and Their String Representations

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. The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a DateTime value is the result of a formatting operation. Formatting is the process of converting a value to its string representation.

Because the appearance of date and time values is dependent on such factors as culture, international standards, application requirements, and personal preference, the DateTime structure offers a great deal of flexibility in formatting date and time values through the overloads of its ToString method. 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. The following example uses the default DateTime..::.ToString()()() method to display the date and time using the short date and long time pattern for the en-US culture, the current culture on the computer on which the example was run.

Visual Basic
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
C#
DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString());
// For en-US culture, displays 3/1/2008 7:00:00 AM

The DateTime..::.ToString(IFormatProvider) method returns the string representation of a date and time value using the short date and long time pattern of a specific culture. 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.

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

The DateTime..::.ToString(String) method returns the string representation of the date and time in a format defined by a standard or custom format specifier and using the formatting conventions of the current culture. 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.

Visual Basic
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("F"))
' Displays Saturday, March 01, 2008 7:00:00 AM
C#
DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F"));
// Displays Saturday, March 01, 2008 7:00:00 AM

The DateTime..::.ToString(String, IFormatProvider) method returns the string representation of the date and time in a format defined by a specific format specifier and using the formatting conventions of a specific culture. The following example uses the DateTime..::.ToString(String, IFormatProvider) method to display the full date and time pattern for the fr-FR culture.

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

Version Considerations

Prior to the .NET Framework version 2.0, the DateTime structure contains a 64-bit field composed of an unused 2-bit field concatenated with a private Ticks field, which is a 62-bit unsigned field that contains the number of ticks that represent the date and time. The value of the Ticks field can be obtained with the Ticks property.

Starting with the .NET Framework 2.0, the DateTime structure contains a 64-bit field composed of a private Kind field concatenated with the Ticks field. The Kind field is a 2-bit field that indicates whether the DateTime structure represents a local time, a Coordinated Universal Time (UTC), or the time in an unspecified time zone. The Kind field is used when performing time conversions between time zones, but not for time comparisons or arithmetic. The value of the Kind field can be obtained with the Kind property.

NoteNote

An alternative to the DateTime structure for working with date and time values in particular time zones is the DateTimeOffset structure. 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. 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. 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, and TimeZoneInfo.

DateTime Values

Descriptions of time values in the DateTime type are often expressed using the Coordinated Universal Time (UTC) standard, which is the internationally recognized name for Greenwich Mean Time (GMT). Coordinated Universal Time is the time as measured at zero degrees longitude, the UTC origin point. Daylight saving time is not applicable to UTC.

Local time is relative to a particular time zone. A time zone is associated with a time zone offset, which is the displacement of the time zone measured in hours from the UTC origin point. In addition, local time is optionally affected by daylight saving time, which adds or subtracts an hour from the length of a day. Consequently, local time is calculated by adding the time zone offset to UTC and adjusting for daylight saving time if necessary. The time zone offset at the UTC origin point is zero.

UTC time is suitable for calculations, comparisons, and storing dates and time in files. Local time is appropriate for display in user interfaces of desktop applications. Time zone-aware applications (such as many Web applications) also need to work with a number of other time zones.

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.

DateTime Operations

A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation.

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.

The DateTime structure itself offers limited support for converting from one time zone to another. 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. However, a full set of time zone conversion methods is available in the TimeZoneInfo class. Using these methods, you can convert the time in any one of the world's time zones to the time in any other time zone.

Calculations and comparisons of DateTime objects are meaningful only if the objects represent times in the same time zone. You can use a TimeZoneInfo object to represent a DateTime value's time zone, although the two are loosely coupled. (That is, a DateTime object does not have a property that returns an object that represents that date and time value's time zone other than the Kind property.) For this reason, 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. For example, you could use a structure that wraps both the DateTime value and the TimeZoneInfo object that represents the DateTime value's time zone. For details on using UTC in calculations and comparisons with DateTime values, see Performing Arithmetic Operations with Dates and Times.

Each DateTime member implicitly uses the Gregorian calendar to perform its operation, with the exception of constructors that specify a calendar, and methods with a parameter derived from IFormatProvider, such as System.Globalization..::.DateTimeFormatInfo, that implicitly specifies a calendar.

Operations by members of the DateTime type take into account details such as leap years and the number of days in a month.

DateTime vs.TimeSpan

The DateTime and TimeSpan value types differ in that a DateTime represents an instant in time whereas a TimeSpan represents a time interval. This means, for example, that you can subtract one instance of DateTime from another to obtain a TimeSpan object that represents the time interval between them. Or you could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future date.

You can add or subtract a time interval from a DateTime object. Time intervals can be negative or positive, can be expressed in units such as ticks or seconds, or can be expressed as a TimeSpan object.

COM Interop Considerations

A DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. However, a DateTime value that specifies only a time does not round-trip as you might expect.

If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. at 3:00 P.M., instead of January, 1, 0001 C.E. at 3:00 P.M. This happens because the .NET Framework and COM assume a default date when only a time is specified. 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.

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. 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. This also means if a date starts its round-trip from COM, the .NET Framework and COM preserve the date.

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.

The following example demonstrates how to compare roughly equivalent DateTime values, accepting a small margin of difference when declaring them equal.

Visual Basic
Class DateTimeTester
   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 Main()
      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 ({0}) ~= d1 ({1}): {2}", _
                        d1, d1, RoughlyEquals(d1, d1, window, freq))
      Console.WriteLine("d1 ({0}) ~= d2 ({1}): {2}", _
                        d1, d2, RoughlyEquals(d1, d2, window, freq))
      Console.WriteLine("d1 ({0}) ~= d3 ({1}): {2}", _
                        d1, d3, RoughlyEquals(d1, d3, window, freq))
      Console.WriteLine("d1 ({0}) ~= d4 ({1}): {2}", _
                        d1, d4, RoughlyEquals(d1, d4, window, freq))
      Console.WriteLine("d1 ({0}) ~= d5 ({1}): {2}", _
                        d1, d5, RoughlyEquals(d1, d5, window, freq))

      Console.WriteLine("d1 ({0}) ~= d6 ({1}): {2}", _
                        d1, d6, RoughlyEquals(d1, d6, window, freq))
      Console.WriteLine("d1 ({0}) ~= d7 ({1}): {2}", _
                        d1, d7, RoughlyEquals(d1, d7, window, freq))
      Console.WriteLine("d1 ({0}) ~= d8 ({1}): {2}", _
                        d1, d8, RoughlyEquals(d1, d8, window, freq))
      Console.WriteLine("d1 ({0}) ~= d9 ({1}): {2}", _
                        d1, d9, RoughlyEquals(d1, d9, window, freq))
   End Sub
End Class
' 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
C#
using System;

class DateTimeTester 
{
   static bool RoughlyEquals(DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds)
   {
      long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds 
                                                     % frequencyInSeconds;

      delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta;

      return Math.Abs(delta) < windowInSeconds;
    }

    public static void Main() 
    {
      int window = 10;
      int freq = 60 * 60 * 2; // 2 hours;

      DateTime d1 = DateTime.Now;

      DateTime d2 = d1.AddSeconds(2 * window);
      DateTime d3 = d1.AddSeconds(-2 * window);
      DateTime d4 = d1.AddSeconds(window / 2);
      DateTime d5 = d1.AddSeconds(-window / 2);

      DateTime d6 = (d1.AddHours(2)).AddSeconds(2 * window);
      DateTime d7 = (d1.AddHours(2)).AddSeconds(-2 * window);
      DateTime d8 = (d1.AddHours(2)).AddSeconds(window / 2);
      DateTime d9 = (d1.AddHours(2)).AddSeconds(-window / 2);

      Console.WriteLine("d1 ({0}) ~= d1 ({1}): {2}",
                        d1, d1, RoughlyEquals(d1, d1, window, freq));
      Console.WriteLine("d1 ({0}) ~= d2 ({1}): {2}", 
                        d1, d2, RoughlyEquals(d1, d2, window, freq));
      Console.WriteLine("d1 ({0}) ~= d3 ({1}): {2}", 
                        d1, d3, RoughlyEquals(d1, d3, window, freq));
      Console.WriteLine("d1 ({0}) ~= d4 ({1}): {2}", 
                        d1, d4, RoughlyEquals(d1, d4, window, freq));
      Console.WriteLine("d1 ({0}) ~= d5 ({1}): {2}", 
                        d1, d5, RoughlyEquals(d1, d5, window, freq));

      Console.WriteLine("d1 ({0}) ~= d6 ({1}): {2}", 
                        d1, d6, RoughlyEquals(d1, d6, window, freq));
      Console.WriteLine("d1 ({0}) ~= d7 ({1}): {2}", 
                        d1, d7, RoughlyEquals(d1, d7, window, freq));
      Console.WriteLine("d1 ({0}) ~= d8 ({1}): {2}", 
                        d1, d8, RoughlyEquals(d1, d8, window, freq));
      Console.WriteLine("d1 ({0}) ~= d9 ({1}): {2}", 
                        d1, d9, RoughlyEquals(d1, d9, window, freq));
    }
}
// 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
Visual C++
bool RoughlyEquals( DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds )
{
   long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds % frequencyInSeconds;
   delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta;
   return Math::Abs( delta ) < windowInSeconds;
}

int main()
{
   int window = 10;
   int freq = 60 * 60 * 2; // 2 hours;

   DateTime d1 = DateTime::Now;
   DateTime d2 = d1.AddSeconds( 2 * window );
   DateTime d3 = d1.AddSeconds(  -2 * window );
   DateTime d4 = d1.AddSeconds( window / 2 );
   DateTime d5 = d1.AddSeconds(  -window / 2 );
   DateTime d6 = (d1.AddHours( 2 )).AddSeconds( 2 * window );
   DateTime d7 = (d1.AddHours( 2 )).AddSeconds(  -2 * window );
   DateTime d8 = (d1.AddHours( 2 )).AddSeconds( window / 2 );
   DateTime d9 = (d1.AddHours( 2 )).AddSeconds(  -window / 2 );

   Console::WriteLine("d1 ({0}) ~= d1 ({1}): {2}",
                      d1, d1, RoughlyEquals(d1, d1, window, freq));
   Console::WriteLine("d1 ({0}) ~= d2 ({1}): {2}", 
                      d1, d2, RoughlyEquals(d1, d2, window, freq));
   Console::WriteLine("d1 ({0}) ~= d3 ({1}): {2}", 
                      d1, d3, RoughlyEquals(d1, d3, window, freq));
   Console::WriteLine("d1 ({0}) ~= d4 ({1}): {2}", 
                      d1, d4, RoughlyEquals(d1, d4, window, freq));
   Console::WriteLine("d1 ({0}) ~= d5 ({1}): {2}", 
                      d1, d5, RoughlyEquals(d1, d5, window, freq));

   Console::WriteLine("d1 ({0}) ~= d6 ({1}): {2}", 
                      d1, d6, RoughlyEquals(d1, d6, window, freq));
   Console::WriteLine("d1 ({0}) ~= d7 ({1}): {2}", 
                      d1, d7, RoughlyEquals(d1, d7, window, freq));
   Console::WriteLine("d1 ({0}) ~= d8 ({1}): {2}", 
                      d1, d8, RoughlyEquals(d1, d8, window, freq));
   Console::WriteLine("d1 ({0}) ~= d9 ({1}): {2}", 
                      d1, d9, RoughlyEquals(d1, d9, window, freq));
}                     
// 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

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.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 XP SP2 x64 Edition, 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.

All members of this type are thread safe. Members that appear to modify instance state actually return a new instance initialized with the new value. 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.

Caution noteCaution

Assigning an instance of this type is not thread safe on all hardware platforms because the binary representation of that instance might be too large to assign in a single atomic operation.

Biblioteca de clases de .NET Framework
DateTime (Estructura)

Representa un instante de tiempo, normalmente expresado en forma de fecha y hora del día.

Espacio de nombres:  System
Ensamblado:  mscorlib (en mscorlib.dll)
Visual Basic
<SerializableAttribute> _
Public Structure DateTime _
    Implements IComparable, IFormattable, IConvertible, ISerializable,  _
    IComparable(Of DateTime), IEquatable(Of DateTime)
C#
[SerializableAttribute]
public struct DateTime : IComparable, IFormattable, 
    IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>
Visual C++
[SerializableAttribute]
public value class DateTime : IComparable, 
    IFormattable, IConvertible, ISerializable, IComparable<DateTime>, 
    IEquatable<DateTime>
F#
[<Sealed>]
[<SerializableAttribute>]
type DateTime =  
    struct
        interface IComparable
        interface IFormattable
        interface IConvertible
        interface ISerializable
        interface IComparable<DateTime>
        interface IEquatable<DateTime>
    end

El tipo DateTime expone los siguientes miembros.

  NombreDescripción
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(Int64)Inicializa una nueva instancia de la estructura DateTime en un número de pasos especificado.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(Int32, Int32, Int32)Inicializa una nueva instancia de la estructura DateTime en el año, mes y día especificados.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateTime(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.
Arriba
  NombreDescripción
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDateObtiene el componente correspondiente a la fecha de esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDayObtiene el día del mes representado por esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDayOfWeekObtiene el día de la semana representado por esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDayOfYearObtiene el día del año representado por esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifHourObtiene el componente correspondiente a la hora de la fecha representada por esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifKindObtiene 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.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifMillisecondObtiene el componente correspondiente a los milisegundos de la fecha representada por esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifMinuteObtiene el componente correspondiente a los minutos de la fecha representada por esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifMonthObtiene el componente correspondiente al mes de la fecha representada por esta instancia.
Propiedad públicaMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifNowObtiene un objeto DateTime que se establece en la fecha y hora actual de este equipo, expresada como hora local.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifSecondObtiene el componente correspondiente a los segundos de la fecha representada por esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifTicksObtiene el número de pasos que representan la fecha y hora de esta instancia.
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifTimeOfDayObtiene la hora del día para esta instancia.
Propiedad públicaMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifTodayObtiene la fecha actual.
Propiedad públicaMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifUtcNowObtiene un objeto DateTime que se establece en la fecha y hora actual del equipo, expresada como hora universal coordinada (UTC)
Propiedad públicaCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifYearObtiene el componente correspondiente al año de la fecha representada por esta instancia.
Arriba
  NombreDescripción
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddDevuelve un nuevo objeto DateTime que suma el valor del objeto TimeSpan especificado al valor de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddDaysDevuelve un nuevo objeto DateTime que suma el número especificado de días al valor de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddHoursDevuelve un nuevo objeto DateTime que suma el número especificado de horas al valor de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddMillisecondsDevuelve un nuevo objeto DateTime que suma el número especificado de milisegundos al valor de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddMinutesDevuelve un nuevo objeto DateTime que suma el número especificado de minutos al valor de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddMonthsDevuelve un nuevo objeto DateTime que suma el número especificado de meses al valor de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddSecondsDevuelve un nuevo objeto DateTime que suma el número especificado de segundos al valor de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddTicksDevuelve un nuevo objeto DateTime que suma el número especificado de pasos al valor de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAddYearsDevuelve un nuevo objeto DateTime que suma el número especificado de años al valor de esta instancia.
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifCompareCompara dos instancias de DateTime y devuelve un entero que indica si la primera instancia es anterior, igual o posterior a la segunda instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifCompareTo(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.
Método públicoCompatible con XNA FrameworkCompareTo(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.
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifDaysInMonthDevuelve el número de días del mes y año especificados.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifEquals(DateTime)Devuelve un valor que indica si esta instancia equivale a la instancia de DateTime especificada.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifEquals(Object)Devuelve un valor que indica si la instancia es igual a un objeto especificado. (Invalida a ValueType..::.Equals(Object)).
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifEquals(DateTime, DateTime)Devuelve un valor que indica si dos instancias de DateTime son iguales.
Método protegidoCompatible con XNA Framework03ybds8y.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áticoFromBinaryDeserializa un valor binario de 64 bits y vuelve a crear un objeto DateTime serializado original.
Método públicoMiembro estáticoCompatible con XNA FrameworkFromFileTimeConvierte la hora de archivo de Windows especificada en una hora local equivalente.
Método públicoMiembro estáticoCompatible con XNA FrameworkFromFileTimeUtcConvierte la hora de archivo de Windows especificada en una hora UTC equivalente.
Método públicoMiembro estáticoCompatible con XNA FrameworkFromOADateDevuelve un DateTime que equivale a la fecha de automatización OLE especificada.
Método públicoCompatible con XNA FrameworkGetDateTimeFormats()()()Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por los especificadores de formato de fecha y hora estándar.
Método públicoCompatible con XNA FrameworkGetDateTimeFormats(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.
Método públicoCompatible con XNA FrameworkGetDateTimeFormats(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.
Método públicoCompatible con XNA FrameworkGetDateTimeFormats(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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifGetHashCodeDevuelve el código hash de esta instancia. (Invalida a ValueType..::.GetHashCode()()()).
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método públicoCompatible con XNA FrameworkGetTypeCodeDevuelve la enumeración TypeCode para el tipo de valor DateTime.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifIsDaylightSavingTimeIndica si esta instancia de DateTime está dentro del intervalo del horario de verano de la zona horaria actual.
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifIsLeapYearDevuelve una indicación en la que se precisa si el año especificado es bisiesto.
Método protegidoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifMemberwiseCloneCrea una copia superficial del objeto Object actual. (Se hereda de Object).
Método públicoMiembro estáticoCompatible con XNA FrameworkParse(String)Convierte la representación de cadena especificada de una fecha y hora en su equivalente DateTime.
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.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 DateTime equivalente, utilizando la información de formato específica de la referencia cultural especificada.
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.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 DateTime equivalente, utilizando la información de formato específica de la referencia cultural y el estilo de formato especificados.
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.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 DateTime 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áticoCompatible con XNA Framework03ybds8y.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 DateTime 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; de lo contrario, se produce una excepción.
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.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 estructura DateTime equivalente, utilizando la matriz de formatos, la información de formato específica de la referencia cultural y el estilo indicados. 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.
Método públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifSpecifyKindCrea un nuevo objeto DateTime que tiene el mismo número de tics 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.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifSubtract(DateTime)Resta la fecha y hora especificadas de esta instancia.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifSubtract(TimeSpan)Resta la duración especificada de esta instancia.
Método públicoToBinarySerializa el objeto DateTime actual a un valor binario de 64 bits que se puede utilizar después para volver a crear el objeto DateTime.
Método públicoCompatible con XNA FrameworkToFileTimeConvierte el valor del objeto DateTime actual en una hora de archivo de Windows.
Método públicoCompatible con XNA FrameworkToFileTimeUtcConvierte el valor del objeto DateTime actual en una hora de archivo de Windows.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifToLocalTimeConvierte el valor del objeto DateTime actual a la hora local.
Método públicoCompatible con XNA FrameworkToLongDateStringConvierte el valor del objeto DateTime actual en su representación de cadena de fecha larga equivalente.
Método públicoCompatible con XNA FrameworkToLongTimeStringConvierte el valor del objeto DateTime actual en su representación de cadena de hora larga equivalente.
Método públicoCompatible con XNA FrameworkToOADateConvierte el valor de esta instancia en la fecha de automatización OLE equivalente.
Método públicoCompatible con XNA FrameworkToShortDateStringConvierte el valor del objeto DateTime actual en su representación de cadena de fecha corta equivalente.
Método públicoCompatible con XNA FrameworkToShortTimeStringConvierte el valor del objeto DateTime actual en su representación de cadena de hora corta equivalente.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifToString()()()Convierte el valor del objeto DateTime actual en su representación de cadena equivalente. (Invalida a ValueType..::.ToString()()()).
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifToString(IFormatProvider)Convierte el valor del objeto DateTime actual en su representación de cadena equivalente utilizando la información de formato específica de la referencia cultural especificada.
Método públicoCompatible con XNA FrameworkToString(String)Convierte el valor del objeto DateTime actual en una representación de cadena equivalente utilizando el formato especificado.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifToString(String, IFormatProvider)Convierte el valor del objeto DateTime actual en su representación de cadena equivalente, utilizando el formato y la información de formato específica de la referencia cultural indicados.
Método públicoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifToUniversalTimeConvierte el valor del objeto DateTime actual a la hora universal coordinada (UCT).
Método públicoMiembro estáticoTryParse(String, DateTime%)Convierte la representación de cadena especificada de una fecha y hora en su objeto DateTime equivalente y devuelve un valor que indica si la conversión tuvo éxito.
Método públicoMiembro estático03ybds8y.PortableClassLibrary(es-es,VS.100).gifTryParse(String, IFormatProvider, DateTimeStyles, DateTime%)Convierte la representación de cadena especificada de una fecha y hora en su equivalente DateTime utilizando 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.
Método públicoMiembro estático03ybds8y.PortableClassLibrary(es-es,VS.100).gifTryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime%)Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTime 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. El método devuelve un valor que indica si la conversión finalizó correctamente.
Método públicoMiembro estático03ybds8y.PortableClassLibrary(es-es,VS.100).gifTryParseExact(String, array<String>[]()[], IFormatProvider, DateTimeStyles, DateTime%)Convierte la representación de cadena que se haya especificado para una fecha y hora en su DateTime 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 al menos uno de los formatos especificados. El método devuelve un valor que indica si la conversión finalizó correctamente.
Arriba
  NombreDescripción
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifAdditionAgrega un intervalo de tiempo especificado a una fecha y hora especificadas, generando una fecha y hora nuevas.
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifEqualityDetermina si dos instancias especificadas de DateTime son iguales.
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifGreaterThanDetermina si un DateTime especificado es mayor que otro DateTime especificado.
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifGreaterThanOrEqualDetermina si un DateTime especificado es mayor o igual que otro DateTime especificado.
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifInequalityDetermina si dos instancias especificadas de DateTime no son iguales.
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifLessThanDetermina si un DateTime especificado es menor que otro DateTime especificado.
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifLessThanOrEqualDetermina si un DateTime especificado es menor o igual que otro DateTime especificado.
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifSubtraction(DateTime, DateTime)Resta una fecha y hora especificadas de otra fecha y hora especificadas y devuelve un intervalo de tiempo.
Operador públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifSubtraction(DateTime, TimeSpan)Resta un intervalo de tiempo especificado de una fecha y hora especificadas y devuelve una fecha y hora nuevas.
Arriba
  NombreDescripción
Campo públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifMaxValueRepresenta el mayor valor posible de DateTime. Este campo es de sólo lectura.
Campo públicoMiembro estáticoCompatible con XNA Framework03ybds8y.PortableClassLibrary(es-es,VS.100).gifMinValueRepresenta el menor valor posible de DateTime. Este campo es de sólo lectura.
Arriba
  NombreDescripción
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToBooleanInfraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToByteInfraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToCharInfraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToDateTimeInfraestructura. Devuelve el objeto DateTime actual.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToDecimalInfraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToDoubleInfraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToInt16Infraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToInt32Infraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToInt64Infraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToSByteInfraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToSingleInfraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToTypeInfraestructura. Convierte el objeto DateTime actual en un objeto de un tipo especificado.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToUInt16Infraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToUInt32Infraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoCompatible con XNA FrameworkIConvertible..::.ToUInt64Infraestructura. No se admite esta conversión. Cualquier intento de utilizar este método produce una excepción InvalidCastException.
Implementación explícita de interfacesMétodo privadoISerializable..::.GetObjectDataRellena un objeto SerializationInfo con los datos necesarios para serializar el objeto DateTime actual.
Arriba

El tipo de valor de DateTime representa fechas y horas cuyos valores están comprendidos entre la medianoche (00:00:00) del 1 de enero de 0001 d.C. (Era Cristiana) y las 23:59:59 del 31 de diciembre de 9999 d.C. (Era cristiana).

Los valores de tiempo se miden 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. (era cristiana) en el calendario GregorianCalendar (excluyendo los pasos que serían agregados por segundos intercalados). Por ejemplo, un valor en pasos de 31241376000000000L representa la fecha de viernes, 1 de enero de 0100 a las 12:00:00 de la noche. Un valor DateTime siempre se expresa en el contexto de un calendario explícito o predeterminado.

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 DateTime, puede utilizar la expresión dateValue.Second + nTicks/Timespan.TicksPerSecond.

Crear instancias de un objeto DateTime

Puede crear un nuevo valor DateTime de cualquiera de las maneras siguientes:

  • Mediante una llamada a cualquiera de las sobrecargas del constructor DateTime que le permiten especificar elementos concretos del valor de fecha y hora (como el año, mes y día o el número de pasos). En la instrucción siguiente se muestra una llamada a uno de los constructores DateTime para crear una fecha con un año, mes, día, hora, minuto y segundo concretos.

    Visual Basic
    Dim date1 As New Date(2008, 5, 1, 8, 30, 52)
    
    C#
    DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
    
  • Mediante cualquier sintaxis específica del compilador para declarar los valores de fecha y hora. Por ejemplo, la instrucción de Visual Basic siguiente inicializa un nuevo valor DateTime.

    Visual Basic
    Dim date1 As Date = #5/1/2008 8:30:52AM#
    
  • Mediante la asignación al objeto DateTime de un valor de fecha y hora devuelto por una propiedad o método. En el ejemplo siguiente se asignan la fecha y hora actuales, la fecha y hora de la Hora universal coordinada (hora UTC) y la fecha actual a tres nuevas variables DateTime.

    Visual Basic
    Dim date1 As Date = Date.Now
    Dim date2 As Date = Date.UtcNow
    Dim date3 As Date = Date.Today
    
    C#
    DateTime date1 = DateTime.Now;
    DateTime date2 = DateTime.UtcNow;
    DateTime date3 = DateTime.Today;
    
  • Con el análisis de la representación de cadena de un valor de fecha y hora. Los métodos Parse, ParseExact, TryParseExact y TryParse convierten una cadena en su valor de fecha y hora equivalente. En el ejemplo siguiente se utiliza el método Parse para analizar una cadena y convertirlo en un valor DateTime.

    Visual Basic
    Dim dateString As String = "5/1/2008 8:30:52 AM"
    Dim date1 As Date = Date.Parse(dateString, _
                             System.Globalization.CultureInfo.InvariantCulture) 
    
    C#
    string dateString = "5/1/2008 8:30:52 AM";
    DateTime date1 = DateTime.Parse(dateString, 
                              System.Globalization.CultureInfo.InvariantCulture); 
    

    Observe que los métodos TryParseExact y TryParse indican si una cadena determinada contiene una representación válida de un valor de DateTime a la vez que realiza la conversión.

  • Mediante una llamada al constructor predeterminado implícito de la estructura DateTime. (Para obtener información detallada sobre el constructor predeterminado implícito de un tipo de valor, vea Tipos de valor (Referencia de C#).) Un equivalente aproximado, para los compiladores que lo admiten, es declarar un valor DateTime sin asignarle explícitamente una fecha y hora. En el ejemplo siguiente se muestra una llamada al constructor predeterminado implícito de DateTime en C# y Visual Basic, así como una declaración de variable DateTime sin asignación en Visual Basic.

    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))
    
    C#
    DateTime 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));
    

Valores DateTime y sus representaciones de cadena

Internamente, todos los valores DateTime se representan como el número de pasos (el número de intervalos de 100 nanosegundos) transcurridos desde la medianoche (00:00:00) del 1 de enero de 0001. El valor DateTime real es independiente de la manera en la que ese valor aparece cuando se mostró en un elemento de la interfaz de usuario o cuando se escribe en un archivo. La apariencia de un valor DateTime es el resultado de una operación de formato. Dar formato es el proceso de convertir un valor en su representación de cadena.

Como la apariencia de los valores de fecha y hora depende de factores como la referencia cultural, normas internacionales, requisitos de aplicación y preferencias personales, la estructura DateTime ofrece una gran flexibilidad para dar formato a los valores de fecha y hora a través de las sobrecargas de su método ToString. El método DateTime..::.ToString()()() predeterminado devuelve la representación de cadena de un valor de fecha y hora utilizando la fecha corta de la referencia cultural actual y el modelo horario largo. En el ejemplo siguiente se utiliza el método DateTime..::.ToString()()() predeterminado para mostrar la fecha y hora utilizando la fecha corta y el modelo horario largo para la referencia cultural en-US, que era la referencia cultural actual del equipo en el que se ejecutó el ejemplo.

Visual Basic
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
C#
DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString());
// For en-US culture, displays 3/1/2008 7:00:00 AM

El método DateTime..::.ToString(IFormatProvider) devuelve la representación de cadena de un valor de fecha y hora utilizando la fecha corta y el modelo horario largo de una referencia cultural concreta. En el ejemplo siguiente se utiliza el método DateTime..::.ToString(IFormatProvider) para mostrar la fecha y hora utilizando la fecha corta y el modelo horario largo para la referencia cultural fr-FR.

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

El método DateTime..::.ToString(String) devuelve la representación de cadena de la fecha y hora en un formato definido por un especificador de formato estándar o personalizado, utilizando las convenciones de formato de la referencia cultural actual. En el ejemplo siguiente se utiliza el método DateTime..::.ToString(String) para mostrar el modelo completo de fecha y hora para la referencia cultural en-US, que era la referencia cultural actual del equipo en el que se ejecutó el ejemplo.

Visual Basic
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("F"))
' Displays Saturday, March 01, 2008 7:00:00 AM
C#
DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F"));
// Displays Saturday, March 01, 2008 7:00:00 AM

El método DateTime..::.ToString(String, IFormatProvider) devuelve la representación de cadena de la fecha y hora en un formato definido por un especificador de formato concreto, utilizando las convenciones de formato de una referencia cultural concreta. En el ejemplo siguiente se utiliza el método DateTime..::.ToString(String, IFormatProvider) para mostrar el modelo completo de fecha y hora utilizando la fecha corta y el modelo horario largo para la referencia cultural fr-FR.

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

Consideraciones de versión

En las versiones anteriores a la versión 2.0 de .NET Framework, la estructura DateTime contiene un campo de 64 bits formado por un campo de 2 bits no utilizados concatenado a un campo privado Ticks, que es un campo sin firma de 62 bits que contiene el número de pasos que representan la fecha y la hora. El valor del campo Ticks se puede obtener con la propiedad Ticks.

A partir de la versión 2.0 de .NET Framework, la estructura DateTime contiene un campo de 64 bits formado por un campo Kind privado concatenado al campo Ticks. El campo Kind es un campo de 2 bits que indica si la estructura DateTime representa una hora local, una hora universal coordinada (UTC) o la hora en una zona horaria no especificada. Este campo se utiliza cuando se realizan conversiones de horas entre zonas horarias, pero no para realizar operaciones aritméticas o de comparación de horas. El valor del campo Kind se puede obtener con la propiedad Kind.

NotaNota

Una alternativa a la estructura DateTime para trabajar en particular con valores de fecha y hora en zonas horarias concretas es la estructura DateTimeOffset. La estructura DateTimeOffset almacena información de fecha y hora en un campo DateTime privado y el número de minutos en que esa fecha y hora difiere de la hora UTC en un campo Int16 privado. Esto permite que un valor de DateTimeOffset refleje la hora en una zona horaria determinada, mientras que un valor de DateTime puede reflejar inequívocamente sólo la hora UTC y la hora de la zona horaria local. Para obtener una explicación de cuándo se debe utilizar la estructura DateTime o la estructura DateTimeOffset al trabajar con valores de fecha y hora, vea Elegir entre DateTime, DateTimeOffset y TimeZoneInfo.

Valores de DateTime

Las descripciones de los valores de hora del tipo DateTime se suelen expresar utilizando el estándar de hora universal coordinada (UTC), que es el nombre con el que se conoce internacionalmente a la hora media de Greenwich (GMT). La hora universal coordinada es la hora que se mide en la longitud cero grados, punto de origen de UTC. El horario de verano no se aplica a UTC.

La hora local está relacionada con una zona horaria determinada. Una zona horaria se asocia a un desplazamiento de zona horaria, que es la diferencia medida en horas entre la zona horaria y el punto de origen de UTC. Además, a la hora local le afecta opcionalmente el horario de verano, que agrega o resta una hora a la duración del día. Por consiguiente, la hora local se calcula agregando el desplazamiento de zona horaria a la hora UTC y haciendo los ajustes oportunos por el horario de verano, en caso necesario. El desplazamiento de zona horaria en el punto de origen de UTC es cero.

La hora UTC es adecuada para los cálculos, las comparaciones y el almacenamiento de fechas y horas en los archivos. La hora local es apropiada para la presentación en las interfaces de usuario de aplicaciones de escritorio. Las aplicaciones que tienen en cuenta la zona horaria (como muchas aplicaciones web) también necesitan trabajar con otras zonas horarias.

Si la propiedad Kind de un objeto DateTime es DateTimeKind..::.Unspecified, no se especifica si la hora representada es la hora local, la hora UTC o una hora de otra zona horaria.

Operaciones con DateTime

Un cálculo utilizando una estructura DateTime, como Add o Subtract, no modifica el valor de la estructura. En su lugar, el cálculo devuelve una nueva estructura DateTime cuyo valor es el resultado del cálculo.

Las operaciones de conversión entre zonas horarias (como entre la hora UTC y la hora local, o entre una zona horaria y otra) tienen en cuenta el horario de verano, aunque las operaciones aritméticas y de comparación no lo hacen.

La propia estructura DateTime proporciona compatibilidad limitada para la conversión de una zona horaria a otra. Puede utilizar el método ToLocalTime para convertir de hora UTC a hora local, o el método ToUniversalTime para convertir de hora local a hora UTC. No obstante, existe un conjunto completo de métodos de conversión de zonas horarias en la clase TimeZoneInfo. Con estos métodos, puede convertir la hora de cualquiera de las zonas horarias del mundo en la hora de cualquier otra zona horaria.

Los cálculos y las comparaciones de objetos DateTime sólo tienen significado si los objetos representan horas de la misma zona horaria. Puede utilizar un objeto TimeZoneInfo para representar la zona horaria de un valor de DateTime, aunque tengan una correspondencia imprecisa. Es decir, un objeto DateTime no tiene una propiedad que devuelva un objeto que represente la zona horaria de ese valor de fecha y hora salvo la propiedad Kind. Por esta razón, en una aplicación que tenga en cuenta la zona horaria, debe basarse en algún mecanismo externo para determinar la zona horaria en que se creó un objeto DateTime. Por ejemplo, puede utilizar una estructura que incluya el valor de DateTime y el objeto TimeZoneInfo que representa la zona horaria del valor de DateTime. Para obtener información detallada sobre el uso de la hora UTC en cálculos y comparaciones con valores DateTime, vea Efectuar operaciones aritméticas con fechas y horas.

Cada miembro de DateTime usa de forma implícita el calendario gregoriano para realizar sus operaciones, excepto los constructores que especifican un calendario y los métodos con un parámetro derivado de IFormatProvider, como System.Globalization..::.DateTimeFormatInfo, que indican implícitamente un calendario.

Las operaciones que realizan los miembros del tipo DateTime tienen en cuenta una serie de detalles, como los años bisiestos y el número de días de un mes.

DateTime vs.Timespan

Los tipos de valor de DateTime y TimeSpan se diferencian en que DateTime representa un instante de tiempo, mientras que TimeSpan representa un intervalo de tiempo. Por ejemplo, esto significa que puede restar una instancia de DateTime de otra para obtener un objeto TimeSpan que representa el intervalo de tiempo entre ellas. O bien, podría sumar un valor TimeSpan positivo al valor DateTime actual para obtener un valor DateTime que representa una fecha futura.

Se puede agregar o restar un intervalo de tiempo a un objeto DateTime. Los intervalos de tiempo pueden ser negativos o positivos y se pueden expresar en unidades como pasos o segundos, o como objetos TimeSpan.

Observaciones sobre la interoperabilidad COM

Se dice que un valor DateTime es de ida y vuelta cuando se transfiere a una aplicación COM y, a continuación, se vuelve a transferir a una aplicación administrada. Sin embargo, la acción de ida y vuelta de un valor de DateTime que especifique sólo una hora no tendrá el resultado que cabría esperar.

Si realiza la operación de ida y vuelta sólo una vez, por ejemplo, a las 3 p.m., la última fecha y hora es diciembre 30, 1899, d.C. a las 3:00 p.m., en lugar del 1 de enero de 0001 de la era cristiana. a las 3:00 p.m. Esto ocurre porque .NET Framework y COM suponen una fecha predeterminada cuando se especifica una sola vez. Sin embargo, el sistema COM supone como fecha base el 30 de diciembre de 1899 de la Era Cristiana. mientras que .NET Framework supone que la fecha base es el 1 de enero de 0001 de la Era Cristiana.

Cuando sólo se pasa una hora de .NET Framework a COM, se realiza un proceso especial que convierte la hora al formato utilizado por COM. Cuando sólo una vez se pasa de COM a .NET Framework, no se realiza ningún procesamiento especial debido a que podrían dañar las fechas y horas legítimas durante o antes del 30 de diciembre de 1899. Esto también significa que si una fecha comienza una acción de ida y vuelta empezando en COM, .NET Framework y COM conservan la fecha.

El comportamiento de .NET Framework y COM supone que si la aplicación ejecuta una acción de ida y vuelta respecto de un objeto DateTime que sólo especifica una hora, la aplicación no puede olvidarse de modificar u omitir los datos erróneos provenientes del objeto DateTime final.

En el ejemplo siguiente se muestra cómo comparar los valores de DateTime más o menos equivalentes, aceptando un pequeño margen de diferencia cuando se les declara iguales.

Visual Basic
Class DateTimeTester
   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 Main()
      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 ({0}) ~= d1 ({1}): {2}", _
                        d1, d1, RoughlyEquals(d1, d1, window, freq))
      Console.WriteLine("d1 ({0}) ~= d2 ({1}): {2}", _
                        d1, d2, RoughlyEquals(d1, d2, window, freq))
      Console.WriteLine("d1 ({0}) ~= d3 ({1}): {2}", _
                        d1, d3, RoughlyEquals(d1, d3, window, freq))
      Console.WriteLine("d1 ({0}) ~= d4 ({1}): {2}", _
                        d1, d4, RoughlyEquals(d1, d4, window, freq))
      Console.WriteLine("d1 ({0}) ~= d5 ({1}): {2}", _
                        d1, d5, RoughlyEquals(d1, d5, window, freq))

      Console.WriteLine("d1 ({0}) ~= d6 ({1}): {2}", _
                        d1, d6, RoughlyEquals(d1, d6, window, freq))
      Console.WriteLine("d1 ({0}) ~= d7 ({1}): {2}", _
                        d1, d7, RoughlyEquals(d1, d7, window, freq))
      Console.WriteLine("d1 ({0}) ~= d8 ({1}): {2}", _
                        d1, d8, RoughlyEquals(d1, d8, window, freq))
      Console.WriteLine("d1 ({0}) ~= d9 ({1}): {2}", _
                        d1, d9, RoughlyEquals(d1, d9, window, freq))
   End Sub
End Class
' 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
C#
using System;

class DateTimeTester 
{
   static bool RoughlyEquals(DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds)
   {
      long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds 
                                                     % frequencyInSeconds;

      delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta;

      return Math.Abs(delta) < windowInSeconds;
    }

    public static void Main() 
    {
      int window = 10;
      int freq = 60 * 60 * 2; // 2 hours;

      DateTime d1 = DateTime.Now;

      DateTime d2 = d1.AddSeconds(2 * window);
      DateTime d3 = d1.AddSeconds(-2 * window);
      DateTime d4 = d1.AddSeconds(window / 2);
      DateTime d5 = d1.AddSeconds(-window / 2);

      DateTime d6 = (d1.AddHours(2)).AddSeconds(2 * window);
      DateTime d7 = (d1.AddHours(2)).AddSeconds(-2 * window);
      DateTime d8 = (d1.AddHours(2)).AddSeconds(window / 2);
      DateTime d9 = (d1.AddHours(2)).AddSeconds(-window / 2);

      Console.WriteLine("d1 ({0}) ~= d1 ({1}): {2}",
                        d1, d1, RoughlyEquals(d1, d1, window, freq));
      Console.WriteLine("d1 ({0}) ~= d2 ({1}): {2}", 
                        d1, d2, RoughlyEquals(d1, d2, window, freq));
      Console.WriteLine("d1 ({0}) ~= d3 ({1}): {2}", 
                        d1, d3, RoughlyEquals(d1, d3, window, freq));
      Console.WriteLine("d1 ({0}) ~= d4 ({1}): {2}", 
                        d1, d4, RoughlyEquals(d1, d4, window, freq));
      Console.WriteLine("d1 ({0}) ~= d5 ({1}): {2}", 
                        d1, d5, RoughlyEquals(d1, d5, window, freq));

      Console.WriteLine("d1 ({0}) ~= d6 ({1}): {2}", 
                        d1, d6, RoughlyEquals(d1, d6, window, freq));
      Console.WriteLine("d1 ({0}) ~= d7 ({1}): {2}", 
                        d1, d7, RoughlyEquals(d1, d7, window, freq));
      Console.WriteLine("d1 ({0}) ~= d8 ({1}): {2}", 
                        d1, d8, RoughlyEquals(d1, d8, window, freq));
      Console.WriteLine("d1 ({0}) ~= d9 ({1}): {2}", 
                        d1, d9, RoughlyEquals(d1, d9, window, freq));
    }
}
// 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
Visual C++
bool RoughlyEquals( DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds )
{
   long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds % frequencyInSeconds;
   delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta;
   return Math::Abs( delta ) < windowInSeconds;
}

int main()
{
   int window = 10;
   int freq = 60 * 60 * 2; // 2 hours;

   DateTime d1 = DateTime::Now;
   DateTime d2 = d1.AddSeconds( 2 * window );
   DateTime d3 = d1.AddSeconds(  -2 * window );
   DateTime d4 = d1.AddSeconds( window / 2 );
   DateTime d5 = d1.AddSeconds(  -window / 2 );
   DateTime d6 = (d1.AddHours( 2 )).AddSeconds( 2 * window );
   DateTime d7 = (d1.AddHours( 2 )).AddSeconds(  -2 * window );
   DateTime d8 = (d1.AddHours( 2 )).AddSeconds( window / 2 );
   DateTime d9 = (d1.AddHours( 2 )).AddSeconds(  -window / 2 );

   Console::WriteLine("d1 ({0}) ~= d1 ({1}): {2}",
                      d1, d1, RoughlyEquals(d1, d1, window, freq));
   Console::WriteLine("d1 ({0}) ~= d2 ({1}): {2}", 
                      d1, d2, RoughlyEquals(d1, d2, window, freq));
   Console::WriteLine("d1 ({0}) ~= d3 ({1}): {2}", 
                      d1, d3, RoughlyEquals(d1, d3, window, freq));
   Console::WriteLine("d1 ({0}) ~= d4 ({1}): {2}", 
                      d1, d4, RoughlyEquals(d1, d4, window, freq));
   Console::WriteLine("d1 ({0}) ~= d5 ({1}): {2}", 
                      d1, d5, RoughlyEquals(d1, d5, window, freq));

   Console::WriteLine("d1 ({0}) ~= d6 ({1}): {2}", 
                      d1, d6, RoughlyEquals(d1, d6, window, freq));
   Console::WriteLine("d1 ({0}) ~= d7 ({1}): {2}", 
                      d1, d7, RoughlyEquals(d1, d7, window, freq));
   Console::WriteLine("d1 ({0}) ~= d8 ({1}): {2}", 
                      d1, d8, RoughlyEquals(d1, d8, window, freq));
   Console::WriteLine("d1 ({0}) ~= d9 ({1}): {2}", 
                      d1, d9, RoughlyEquals(d1, d9, window, freq));
}                     
// 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

.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Compatible con:

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, 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 de este tipo son seguros para la ejecución de subprocesos. Los miembros que aparecen para modificar el estado de la instancia devuelven una nueva instancia inicializada con el nuevo valor. Al igual que con cualquier otro tipo, la lectura y escritura en una variable compartida que contiene una instancia de este tipo deben protegerse mediante un bloqueo para garantizar la seguridad para subprocesos.

Nota de precauciónPrecaución

La asignación de una instancia de este tipo no es segura para subprocesos en todas las plataformas de hardware, porque la representación binaria de esta instancia puede ser demasiado grande para la asignación en una sola operación atómica.

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