.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)

Syntax
<SerializableAttribute> _
Public Structure DateTime _
Implements IComparable, IFormattable, IConvertible, ISerializable, _
IComparable(Of DateTime), IEquatable(Of DateTime)
[SerializableAttribute]
public struct DateTime : IComparable, IFormattable,
IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>
[SerializableAttribute]
public value class DateTime : IComparable,
IFormattable, IConvertible, ISerializable, IComparable<DateTime>,
IEquatable<DateTime>
[<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.

Constructors
|
| Name | Description |
|---|
.gif) .gif) .gif) | DateTime(Int64) | Initializes a new instance of the DateTime structure to a specified number of ticks. | .gif) .gif) .gif) | DateTime(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. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32) | Initializes a new instance of the DateTime structure to the specified year, month, and day. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Calendar) | Initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Int32, Int32, Int32) | Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second. | .gif) .gif) .gif) | DateTime(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. | .gif) .gif) .gif) | DateTime(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. | .gif) .gif) .gif) | DateTime(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. | .gif) .gif) .gif) | DateTime(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. | .gif) .gif) .gif) | DateTime(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. | .gif) .gif) .gif) | DateTime(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

Methods
|
| Name | Description |
|---|
.gif) .gif) .gif) | Add | Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance. | .gif) .gif) .gif) | AddDays | Returns a new DateTime that adds the specified number of days to the value of this instance. | .gif) .gif) .gif) | AddHours | Returns a new DateTime that adds the specified number of hours to the value of this instance. | .gif) .gif) .gif) | AddMilliseconds | Returns a new DateTime that adds the specified number of milliseconds to the value of this instance. | .gif) .gif) .gif) | AddMinutes | Returns a new DateTime that adds the specified number of minutes to the value of this instance. | .gif) .gif) .gif) | AddMonths | Returns a new DateTime that adds the specified number of months to the value of this instance. | .gif) .gif) .gif) | AddSeconds | Returns a new DateTime that adds the specified number of seconds to the value of this instance. | .gif) .gif) .gif) | AddTicks | Returns a new DateTime that adds the specified number of ticks to the value of this instance. | .gif) .gif) .gif) | AddYears | Returns a new DateTime that adds the specified number of years to the value of this instance. | .gif) .gif) .gif) .gif) | Compare | Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. | .gif) .gif) .gif) | CompareTo(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. | .gif) .gif) | CompareTo(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. | .gif) .gif) .gif) .gif) | DaysInMonth | Returns the number of days in the specified month and year. | .gif) .gif) .gif) | Equals(DateTime) | Returns a value indicating whether this instance is equal to the specified DateTime instance. | .gif) .gif) .gif) | Equals(Object) | Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType..::.Equals(Object).) | .gif) .gif) .gif) .gif) | Equals(DateTime, DateTime) | Returns a value indicating whether two instances of DateTime are equal. | .gif) .gif) .gif) | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | .gif) .gif) | FromBinary | Deserializes a 64-bit binary value and recreates an original serialized DateTime object. | .gif) .gif) .gif) | FromFileTime | Converts the specified Windows file time to an equivalent local time. | .gif) .gif) .gif) | FromFileTimeUtc | Converts the specified Windows file time to an equivalent UTC time. | .gif) .gif) .gif) | FromOADate | Returns a DateTime equivalent to the specified OLE Automation Date. | .gif) .gif) | GetDateTimeFormats()()() | Converts the value of this instance to all the string representations supported by the standard date and time format specifiers. | .gif) .gif) | GetDateTimeFormats(Char) | Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier. | .gif) .gif) | GetDateTimeFormats(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. | .gif) .gif) | GetDateTimeFormats(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. | .gif) .gif) .gif) | GetHashCode | Returns the hash code for this instance. (Overrides ValueType..::.GetHashCode()()().) | .gif) .gif) .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) .gif) | GetTypeCode | Returns the TypeCode for value type DateTime. | .gif) .gif) .gif) | IsDaylightSavingTime | Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone. | .gif) .gif) .gif) .gif) | IsLeapYear | Returns an indication whether the specified year is a leap year. | .gif) .gif) .gif) | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) .gif) .gif) | Parse(String) | Converts the specified string representation of a date and time to its DateTime equivalent. | .gif) .gif) .gif) .gif) | Parse(String, IFormatProvider) | Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information. | .gif) .gif) .gif) .gif) | Parse(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. | .gif) .gif) .gif) .gif) | ParseExact(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. | .gif) .gif) .gif) .gif) | ParseExact(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. | .gif) .gif) .gif) .gif) | ParseExact(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. | .gif) .gif) .gif) .gif) | SpecifyKind | Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value. | .gif) .gif) .gif) | Subtract(DateTime) | Subtracts the specified date and time from this instance. | .gif) .gif) .gif) | Subtract(TimeSpan) | Subtracts the specified duration from this instance. | .gif) | ToBinary | Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object. | .gif) .gif) | ToFileTime | Converts the value of the current DateTime object to a Windows file time. | .gif) .gif) | ToFileTimeUtc | Converts the value of the current DateTime object to a Windows file time. | .gif) .gif) .gif) | ToLocalTime | Converts the value of the current DateTime object to local time. | .gif) .gif) | ToLongDateString | Converts the value of the current DateTime object to its equivalent long date string representation. | .gif) .gif) | ToLongTimeString | Converts the value of the current DateTime object to its equivalent long time string representation. | .gif) .gif) | ToOADate | Converts the value of this instance to the equivalent OLE Automation date. | .gif) .gif) | ToShortDateString | Converts the value of the current DateTime object to its equivalent short date string representation. | .gif) .gif) | ToShortTimeString | Converts the value of the current DateTime object to its equivalent short time string representation. | .gif) .gif) .gif) | ToString()()() | Converts the value of the current DateTime object to its equivalent string representation. (Overrides ValueType..::.ToString()()().) | .gif) .gif) .gif) | ToString(IFormatProvider) | Converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information. | .gif) .gif) | ToString(String) | Converts the value of the current DateTime object to its equivalent string representation using the specified format. | .gif) .gif) .gif) | ToString(String, IFormatProvider) | Converts the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information. | .gif) .gif) .gif) | ToUniversalTime | Converts the value of the current DateTime object to Coordinated Universal Time (UTC). | .gif) .gif) | TryParse(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. | .gif) .gif) .gif) | TryParse(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. | .gif) .gif) .gif) | TryParseExact(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. | .gif) .gif) .gif) | TryParseExact(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

Explicit Interface Implementations

Remarks
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. Instantiating a DateTime ObjectYou 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.
Dim date1 As New Date(2008, 5, 1, 8, 30, 52)
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.
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.
Dim date1 As Date = Date.Now
Dim date2 As Date = Date.UtcNow
Dim date3 As Date = Date.Today
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.
Dim dateString As String = "5/1/2008 8:30:52 AM"
Dim date1 As Date = Date.Parse(dateString, _
System.Globalization.CultureInfo.InvariantCulture)
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.
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))
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 RepresentationsInternally, 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.
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
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.
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
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.
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("F"))
' Displays Saturday, March 01, 2008 7:00:00 AM
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.
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
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 ConsiderationsPrior 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. Note |
|---|
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 ValuesDescriptions 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 OperationsA 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.TimeSpanThe 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 ConsiderationsA 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.

Examples
The following example demonstrates how to compare roughly equivalent DateTime values, accepting a small margin of difference when declaring them equal.
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
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
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

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

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows 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.

Thread Safety
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 |
|---|
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. |

See Also
|
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)

Sintaxis
<SerializableAttribute> _
Public Structure DateTime _
Implements IComparable, IFormattable, IConvertible, ISerializable, _
IComparable(Of DateTime), IEquatable(Of DateTime)
[SerializableAttribute]
public struct DateTime : IComparable, IFormattable,
IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>
[SerializableAttribute]
public value class DateTime : IComparable,
IFormattable, IConvertible, ISerializable, IComparable<DateTime>,
IEquatable<DateTime>
[<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.

Constructores
|
| Nombre | Descripción |
|---|
.gif) .gif) .gif) | DateTime(Int64) | Inicializa una nueva instancia de la estructura DateTime en un número de pasos especificado. | .gif) .gif) .gif) | DateTime(Int64, DateTimeKind) | Inicializa una nueva instancia de la estructura DateTime en el número de pasos y hora universal coordinada (UTC) u hora local especificados. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32) | Inicializa una nueva instancia de la estructura DateTime en el año, mes y día especificados. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Calendar) | Inicializa una nueva instancia de la estructura DateTime en el año, mes y día especificados para el calendario determinado. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Int32, Int32, Int32) | Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto y segundo especificados. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) | Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo, y hora universal coordinada (UTC) u hora local especificados. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar) | Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto y segundo especificados para el calendario indicado. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32) | Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo y milisegundo especificados. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) | Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo, milisegundo, y hora universal coordinada (UTC) u hora local especificados. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar) | Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo y milisegundo especificados para el calendario indicado. | .gif) .gif) .gif) | DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind) | Inicializa una nueva instancia de la estructura DateTime en el año, mes, día, hora, minuto, segundo, milisegundo, y hora universal coordinada (UTC) u hora local especificados para el calendario indicado. | Arriba

Métodos
|
| Nombre | Descripción |
|---|
.gif) .gif) .gif) | Add | Devuelve un nuevo objeto DateTime que suma el valor del objeto TimeSpan especificado al valor de esta instancia. | .gif) .gif) .gif) | AddDays | Devuelve un nuevo objeto DateTime que suma el número especificado de días al valor de esta instancia. | .gif) .gif) .gif) | AddHours | Devuelve un nuevo objeto DateTime que suma el número especificado de horas al valor de esta instancia. | .gif) .gif) .gif) | AddMilliseconds | Devuelve un nuevo objeto DateTime que suma el número especificado de milisegundos al valor de esta instancia. | .gif) .gif) .gif) | AddMinutes | Devuelve un nuevo objeto DateTime que suma el número especificado de minutos al valor de esta instancia. | .gif) .gif) .gif) | AddMonths | Devuelve un nuevo objeto DateTime que suma el número especificado de meses al valor de esta instancia. | .gif) .gif) .gif) | AddSeconds | Devuelve un nuevo objeto DateTime que suma el número especificado de segundos al valor de esta instancia. | .gif) .gif) .gif) | AddTicks | Devuelve un nuevo objeto DateTime que suma el número especificado de pasos al valor de esta instancia. | .gif) .gif) .gif) | AddYears | Devuelve un nuevo objeto DateTime que suma el número especificado de años al valor de esta instancia. | .gif) .gif) .gif) .gif) | Compare | Compara dos instancias de DateTime y devuelve un entero que indica si la primera instancia es anterior, igual o posterior a la segunda instancia. | .gif) .gif) .gif) | CompareTo(DateTime) | Compara el valor de esta instancia con un valor de DateTime especificado y devuelve un entero que indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado. | .gif) .gif) | CompareTo(Object) | Compara el valor de esta instancia con un objeto especificado que contiene un valor de DateTime especificado y devuelve un entero que indica si esta instancia es anterior, igual o posterior al valor de DateTime especificado. | .gif) .gif) .gif) .gif) | DaysInMonth | Devuelve el número de días del mes y año especificados. | .gif) .gif) .gif) | Equals(DateTime) | Devuelve un valor que indica si esta instancia equivale a la instancia de DateTime especificada. | .gif) .gif) .gif) | Equals(Object) | Devuelve un valor que indica si la instancia es igual a un objeto especificado. (Invalida a ValueType..::.Equals(Object)). | .gif) .gif) .gif) .gif) | Equals(DateTime, DateTime) | Devuelve un valor que indica si dos instancias de DateTime son iguales. | .gif) .gif) .gif) | Finalize | Permite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados. (Se hereda de Object). | .gif) .gif) | FromBinary | Deserializa un valor binario de 64 bits y vuelve a crear un objeto DateTime serializado original. | .gif) .gif) .gif) | FromFileTime | Convierte la hora de archivo de Windows especificada en una hora local equivalente. | .gif) .gif) .gif) | FromFileTimeUtc | Convierte la hora de archivo de Windows especificada en una hora UTC equivalente. | .gif) .gif) .gif) | FromOADate | Devuelve un DateTime que equivale a la fecha de automatización OLE especificada. | .gif) .gif) | GetDateTimeFormats()()() | Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por los especificadores de formato de fecha y hora estándar. | .gif) .gif) | GetDateTimeFormats(Char) | Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por el especificador de formato de fecha y hora estándar indicado. | .gif) .gif) | GetDateTimeFormats(IFormatProvider) | Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por los especificadores de formato de fecha y hora estándar y la información de formato específica de la referencia cultural especificada. | .gif) .gif) | GetDateTimeFormats(Char, IFormatProvider) | Convierte el valor de esta instancia en todas las representaciones de cadena admitidas por el especificador de formato de fecha y hora estándar y la información de formato específica de la referencia cultural especificados. | .gif) .gif) .gif) | GetHashCode | Devuelve el código hash de esta instancia. (Invalida a ValueType..::.GetHashCode()()()). | .gif) .gif) .gif) | GetType | Obtiene el objeto Type de la instancia actual. (Se hereda de Object). | .gif) .gif) | GetTypeCode | Devuelve la enumeración TypeCode para el tipo de valor DateTime. | .gif) .gif) .gif) | IsDaylightSavingTime | Indica si esta instancia de DateTime está dentro del intervalo del horario de verano de la zona horaria actual. | .gif) .gif) .gif) .gif) | IsLeapYear | Devuelve una indicación en la que se precisa si el año especificado es bisiesto. | .gif) .gif) .gif) | MemberwiseClone | Crea una copia superficial del objeto Object actual. (Se hereda de Object). | .gif) .gif) .gif) | Parse(String) | Convierte la representación de cadena especificada de una fecha y hora en su equivalente DateTime. | .gif) .gif) .gif) .gif) | Parse(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. | .gif) .gif) .gif) .gif) | Parse(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. | .gif) .gif) .gif) .gif) | ParseExact(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. | .gif) .gif) .gif) .gif) | ParseExact(String, String, IFormatProvider, DateTimeStyles) | Convierte la representación de cadena que se haya especificado para una fecha y hora en su 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. | .gif) .gif) .gif) .gif) | ParseExact(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. | .gif) .gif) .gif) .gif) | SpecifyKind | Crea 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. | .gif) .gif) .gif) | Subtract(DateTime) | Resta la fecha y hora especificadas de esta instancia. | .gif) .gif) .gif) | Subtract(TimeSpan) | Resta la duración especificada de esta instancia. | .gif) | ToBinary | Serializa el objeto DateTime actual a un valor binario de 64 bits que se puede utilizar después para volver a crear el objeto DateTime. | .gif) .gif) | ToFileTime | Convierte el valor del objeto DateTime actual en una hora de archivo de Windows. | .gif) .gif) | ToFileTimeUtc | Convierte el valor del objeto DateTime actual en una hora de archivo de Windows. | .gif) .gif) .gif) | ToLocalTime | Convierte el valor del objeto DateTime actual a la hora local. | .gif) .gif) | ToLongDateString | Convierte el valor del objeto DateTime actual en su representación de cadena de fecha larga equivalente. | .gif) .gif) | ToLongTimeString | Convierte el valor del objeto DateTime actual en su representación de cadena de hora larga equivalente. | .gif) .gif) | ToOADate | Convierte el valor de esta instancia en la fecha de automatización OLE equivalente. | .gif) .gif) | ToShortDateString | Convierte el valor del objeto DateTime actual en su representación de cadena de fecha corta equivalente. | .gif) .gif) | ToShortTimeString | Convierte el valor del objeto DateTime actual en su representación de cadena de hora corta equivalente. | .gif) .gif) .gif) | ToString()()() | Convierte el valor del objeto DateTime actual en su representación de cadena equivalente. (Invalida a ValueType..::.ToString()()()). | .gif) .gif) .gif) | ToString(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. | .gif) .gif) | ToString(String) | Convierte el valor del objeto DateTime actual en una representación de cadena equivalente utilizando el formato especificado. | .gif) .gif) .gif) | ToString(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. | .gif) .gif) .gif) | ToUniversalTime | Convierte el valor del objeto DateTime actual a la hora universal coordinada (UCT). | .gif) .gif) | TryParse(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. | .gif) .gif) .gif) | TryParse(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. | .gif) .gif) .gif) | TryParseExact(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. | .gif) .gif) .gif) | TryParseExact(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

Implementaciones explícitas de interfaces

Comentarios
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. Crear instancias de un objeto DateTimePuede 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.
Dim date1 As New Date(2008, 5, 1, 8, 30, 52)
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.
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.
Dim date1 As Date = Date.Now
Dim date2 As Date = Date.UtcNow
Dim date3 As Date = Date.Today
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.
Dim dateString As String = "5/1/2008 8:30:52 AM"
Dim date1 As Date = Date.Parse(dateString, _
System.Globalization.CultureInfo.InvariantCulture)
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.
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))
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 cadenaInternamente, 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.
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
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.
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
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.
Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("F"))
' Displays Saturday, March 01, 2008 7:00:00 AM
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.
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
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ónEn 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. Nota |
|---|
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 DateTimeLas 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 DateTimeUn 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.TimespanLos 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 COMSe 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.

Ejemplos
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.
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
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
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

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

Plataformas
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.

Seguridad para subprocesos
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. Precaució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. |

Vea también
|