Export (0) Print
Expand All

DateTime Structure

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

To browse the .NET Framework source code for this type, see the Reference Source.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[<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 LibrarySupported in .NET for Windows Store appsDateTime(Int64)Initializes a new instance of the DateTime structure to a specified number of ticks.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsDateTime(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 LibrarySupported in .NET for Windows Store appsDateTime(Int32, Int32, Int32)Initializes a new instance of the DateTime structure to the specified year, month, and day.
Public methodSupported by the XNA FrameworkDateTime(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 LibrarySupported in .NET for Windows Store appsDateTime(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 LibrarySupported in .NET for Windows Store appsDateTime(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 FrameworkDateTime(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 LibrarySupported in .NET for Windows Store appsDateTime(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 LibrarySupported in .NET for Windows Store appsDateTime(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 FrameworkDateTime(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 FrameworkDateTime(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 LibrarySupported in .NET for Windows Store appsDateGets the date component of this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsDayGets the day of the month represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsDayOfWeekGets the day of the week represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsDayOfYearGets the day of the year represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsHourGets the hour component of the date represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsKindGets 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 LibrarySupported in .NET for Windows Store appsMillisecondGets the milliseconds component of the date represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMinuteGets the minute component of the date represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMonthGets the month component of the date represented by this instance.
Public propertyStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsNowGets 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 LibrarySupported in .NET for Windows Store appsSecondGets the seconds component of the date represented by this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsTicksGets the number of ticks that represent the date and time of this instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsTimeOfDayGets the time of day for this instance.
Public propertyStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsTodayGets the current date.
Public propertyStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsUtcNowGets 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 LibrarySupported in .NET for Windows Store appsYearGets the year component of the date represented by this instance.
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsAddReturns 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 LibrarySupported in .NET for Windows Store appsAddDaysReturns 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 LibrarySupported in .NET for Windows Store appsAddHoursReturns 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 LibrarySupported in .NET for Windows Store appsAddMillisecondsReturns 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 LibrarySupported in .NET for Windows Store appsAddMinutesReturns 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 LibrarySupported in .NET for Windows Store appsAddMonthsReturns 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 LibrarySupported in .NET for Windows Store appsAddSecondsReturns 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 LibrarySupported in .NET for Windows Store appsAddTicksReturns 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 LibrarySupported in .NET for Windows Store appsAddYearsReturns 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 LibrarySupported in .NET for Windows Store appsCompareCompares 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 LibrarySupported in .NET for Windows Store appsCompareTo(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 LibrarySupported in .NET for Windows Store appsDaysInMonthReturns the number of days in the specified month and year.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(DateTime)Returns a value indicating whether the value of this instance is equal to the value of the specified DateTime instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(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 LibrarySupported in .NET for Windows Store appsEquals(DateTime, DateTime)Returns a value indicating whether two DateTime instances have the same date and time value.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsFromBinaryDeserializes a 64-bit binary value and recreates an original serialized DateTime object.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFromFileTimeConverts the specified Windows file time to an equivalent local time.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFromFileTimeUtcConverts 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 FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDateTimeFormats()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 FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDateTimeFormats(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 FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDateTimeFormats(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 FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDateTimeFormats(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 LibrarySupported in .NET for Windows Store appsGetHashCodeReturns the hash code for this instance. (Overrides ValueType.GetHashCode().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets 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 LibrarySupported in .NET for Windows Store appsIsDaylightSavingTimeIndicates 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 LibrarySupported in .NET for Windows Store appsIsLeapYearReturns an indication whether the specified year is a leap year.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParse(String)Converts the string representation of a date and time to its DateTime equivalent.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParse(String, IFormatProvider)Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParse(String, IFormatProvider, DateTimeStyles)Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and formatting style.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParseExact(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 LibrarySupported in .NET for Windows Store appsParseExact(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 LibrarySupported in .NET for Windows Store appsParseExact(String, 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 LibrarySupported in .NET for Windows Store appsSpecifyKindCreates 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 LibrarySupported in .NET for Windows Store appsSubtract(DateTime)Subtracts the specified date and time from this instance.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsSubtract(TimeSpan)Subtracts the specified duration from this instance.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsToBinarySerializes 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 FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToFileTimeConverts the value of the current DateTime object to a Windows file time.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToFileTimeUtcConverts the value of the current DateTime object to a Windows file time.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToLocalTimeConverts 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 LibrarySupported in .NET for Windows Store appsToString()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 LibrarySupported in .NET for Windows Store appsToString(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 FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToString(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 LibrarySupported in .NET for Windows Store appsToString(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 LibrarySupported in .NET for Windows Store appsToUniversalTimeConverts the value of the current DateTime object to Coordinated Universal Time (UTC).
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryParse(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 LibrarySupported in .NET for Windows Store appsTryParse(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 LibrarySupported in .NET for Windows Store appsTryParseExact(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 LibrarySupported in .NET for Windows Store appsTryParseExact(String, 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 LibrarySupported in .NET for Windows Store appsAdditionAdds 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 LibrarySupported in .NET for Windows Store appsEqualityDetermines whether two specified instances of DateTime are equal.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGreaterThanDetermines whether one specified DateTime is later than another specified DateTime.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGreaterThanOrEqualDetermines whether one specified DateTime represents a date and time that is the same as or later than another specified DateTime.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsInequalityDetermines whether two specified instances of DateTime are not equal.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsLessThanDetermines whether one specified DateTime is earlier than another specified DateTime.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsLessThanOrEqualDetermines whether one specified DateTime represents a date and time that is the same as or earlier than another specified DateTime.
Public operatorStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsSubtraction(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 LibrarySupported in .NET for Windows Store appsSubtraction(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 LibrarySupported in .NET for Windows Store appsMaxValueRepresents the largest possible value of DateTime. This field is read-only.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMinValueRepresents the smallest possible value of DateTime. This field is read-only.
Top

  NameDescription
Explicit interface implemetationPrivate methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsIComparable.CompareToCompares the current instance with another object of the same type and returns an integer that indicates whether this instance precedes, follows, or occurs in the same position in the sort order as the other object.
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

NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

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

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.

In this section:

Instantiating a DateTime object
DateTime values and their string representations
Converting strings to DateTime values
Version considerations
DateTime values
DateTime operations
DateTime vs. TimeSpan
Persisting DateTime values
COM interop considerations

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.

    No code example is currently available or this language may not be supported.
  • 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.

    No code example is currently available or this language may not be supported.
  • 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.

    No code example is currently available or this language may not be supported.

    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.

    No code example is currently available or this language may not be supported.

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.

No code example is currently available or this language may not be supported.

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.

No code example is currently available or this language may not be supported.

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.

No code example is currently available or this language may not be supported.

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.

No code example is currently available or this language may not be supported.

For more information about formatting DateTime values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

Converting strings to DateTime values

Parsing involves converting the string representation of a date and time to a DateTime value. Typically, date and time strings have two different usages in applications:

  • They represent a date and time that can take a variety of forms and that reflect the conventions of either the current culture or a specific culture. For example, an application may allow a user whose current culture is en-US to input a date value as "12/15/2013" or "December 15, 2013", and allow a user whose current culture is en-GB to input a date value as "15/12/2013" or "15 December 2013".

  • They represent a date and time in a predefined format. For example, an application may serialize a date as "20130103" independently of the culture on which the app is running, or it may require that a date be input in the current culture's short date format.

You can use the Parse or TryParse method to convert a string that might reflect one of the common date and time formats used by a culture to a DateTime value. The following example shows how you can use TryParse to convert date strings in a number of different culture-specific formats to a DateTime value. It changes the current culture to English (Great Britain) and calls the GetDateTimeFormats() method to generate an array of date and time strings. It then passes each element in the array to the TryParse method. The output from the example shows that the parsing method was able to successfully convert each of the culture-specific date and time strings.

No code example is currently available or this language may not be supported.

You can use the TryParse and TryParseExact methods to convert a date and time string that must match a particular format or formats to a DateTime value. You specify the required format or formats as a parameter to the parsing method by using one or more standard or custom date and time format strings. The following example uses the TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to DateTime values.

No code example is currently available or this language may not be supported.

The Parse and ParseExact methods throw an exception if the string to be converted to a DateTime value cannot be parsed. The TryParse and TryParseExact methods return a Boolean value that indicates whether the conversion succeeded or failed. Because the parsing operation for date and time strings, particularly if strings are input by users, tends to have a high failure rate, and because exception handling is expensive, you should use the TryParse or TryParseExact methods in scenarios where performance is important or conversions are subject to a high rate of failure.

For more information about parsing date and time values, see Parsing Date and Time Strings.

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.

Two other common operations with DateTime values involve converting a date and time value to or from its string representation. The process of converting a DateTime value to its string representation is a formatting operation; for more information about formatting, see DateTime values and their string representations. The process of converting the string representation of a date and time to a DateTime value is a parsing operation; for more information about parsing, see Converting strings to DateTime values.

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.

Persisting DateTime values

You can persist DateTime values in four ways:

Regardless of which technique you choose, you must ensure that the routine that restores the DateTime values doesn't lose data or throw an exception. DateTime values should round-trip. That is, the original value and the restored value should be the same. And if the original DateTime value represents a single instant of time, it should identify the same moment of time when it's restored.

To successfully restore DateTime values that are persisted as strings, follow these rules:

  • Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the ToString overload to save the string by using the conventions of the invariant culture, and call the Parse(String, IFormatProvider, DateTimeStyles) or TryParse(String, IFormatProvider, DateTimeStyles, DateTime) overload to restore the string by using the conventions of the invariant culture. Never use the ToString(), Parse(String), or TryParse(String, DateTime) overloads, which use the conventions of the current thread culture.

  • If the data represents a single moment of time, ensure that it represents the same moment in time when it's restored, even if it's restored on a system that uses a different time zone. To do this, you convert the DateTime value to Coordinated Universal Time (UTC) before saving it. You can also serialize the value along with time zone information; for more information about this approach, see Serializing DateTime and time zone data.

The most common error made when persisting DateTime values as strings is to rely on the formatting conventions of the default or current culture. Problems arise if the current culture is different when saving and restoring the strings. The following example illustrates these problems. It saves five dates using the formatting conventions of the current culture, which in this case is English (United States). It restores the dates using the formatting conventions of the current culture, which in this case is English (Great Britain). Because the formatting conventions of the two cultures are different, two of the dates can't be restored, and the remaining three dates are interpreted incorrectly. Also, if the original date and time values represent single moments in time, the restored times are incorrect because time zone information is lost.

No code example is currently available or this language may not be supported.

To round-trip DateTime values successfully, follow these steps:

  1. If the values represent single moments of time, convert them from the local time to UTC by calling the ToUniversalTime method.

  2. Convert the dates to their string representations by calling the ToString(String, IFormatProvider) or String.Format(IFormatProvider, String, Object[]) overload. Use the formatting conventions of the invariant culture by specifying CultureInfo.InvariantCulture as the provider argument. Specify that the value should round-trip by using the "O" or "R" standard format string.

  3. When you call the Parse(String, IFormatProvider, DateTimeStyles) or TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method.

To restore the persisted DateTime values without data loss, do the following:

  1. Parse the data by calling the ParseExact or TryParseExact overload. Specify [F:J#Sys.CultureInfo.InvariantCulture] as the provider argument, and use the same standard format string you used for the format argument during conversion. Include the DateTimeStyles.RoundTripKind value in the styles argument.

  2. If the DateTime values represent single moments in time, call the ToLocalTime method to convert the parsed date from UTC to local time.

The following example uses the invariant culture and the "O" standard format string to ensure that DateTime values that are saved and restored represent the same moment in time regardless of the system, culture, or time zone of the source and target systems.

No code example is currently available or this language may not be supported.

Instead of persisting a DateTime value as a string, you can persist it as an Int64 value that represents a number of ticks. In this case, you don't have to consider the culture of the systems the DateTime values are persisted and restored on.

To persist a DateTime value as an integer:

  • If the DateTime values represent single moments in time, convert them to UTC by calling the ToUniversalTime method.

  • Retrieve the number of ticks represented by the DateTime value from its Ticks property.

To restore a DateTime value that has been persisted as an integer:

  1. Instantiate a new DateTime object by passing the Int64 value to the DateTime(Int64) constructor.

  2. If the DateTime value represents a single moment in time, convert it from UTC to the local time by calling the ToLocalTime method.

The following example persists an array of DateTime values as integers on a system in the U.S. Pacific Time zone. It restores it on a system in the UTC zone. The file that contains the integers includes an Int32 value that indicates the total number of Int64 values that immediately follow it.

No code example is currently available or this language may not be supported.

Instead of saving DateTime values as strings or integers, which you then have to convert back to DateTime values, you can persist DateTime values through serialization to a stream or file, and then restore them through deserialization. In this case, DateTime data is serialized in some specified object format, and the objects are restored when they are deserialized. A formatter or serializer, such as XmlSerializer or BinaryFormatter, handles the process of serialization and deserialization. For more information about serialization and the types of serialization supported by the .NET Framework, see Serialization.

The following example uses the XmlSerializer class to serialize and deserialize DateTime values that represent all leap year days in the twenty-first century. The output represents the result if the example is run on a system whose current culture is English (Great Britain). Because we've deserialized the DateTime object itself, the code doesn't have to handle cultural differences in date and time formats.

No code example is currently available or this language may not be supported.

The previous example doesn't include time information. However, if a DateTime value represents a moment in time and is expressed as a local time, you should convert it from local time to UTC before serializing it by calling the ToUniversalTime method. After you deserialize it, you should convert it from UTC to local time by calling the ToLocalTime method. The following example uses the BinaryFormatter class to serialize DateTime data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the UTC zone.

No code example is currently available or this language may not be supported.

The previous examples have all assumed that DateTime values are expressed as local times, and converted the values between UTC and local time so they reflect the same moment in time on the source and target systems. DateTime values may also reflect moments in time in a time zone other than local and UTC. In this case, because the DateTime structure is not time zone-aware, you have to serialize both the DateTime value and the TimeZoneInfo object that represents its time zone. To do this, create a type whose fields include both the DateTime value and its time zone. The following example defines a DateWithTimeZone structure that illustrates how this might be done.

No code example is currently available or this language may not be supported.
Important noteImportant

The DateWithTimeZone structure is used in the next two examples, which serialize and deserialize an array of DateWithTimeZone objects. To run the examples, first create a class library that contains the DateWithTimeZone structure, and then add a reference to it when you compile each example.

By using the DateWithTimeZone structure , you can then persist date and time along with time zone information. The following example uses the BinaryFormatter class to serialize an array of DateWithTimeZone objects.

No code example is currently available or this language may not be supported.

The following example then calls the BinaryFormatter.Deserialize method to deserialize it.

No code example is currently available or this language may not be supported.

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.

No code example is currently available or this language may not be supported.

.NET Framework

Supported in: 4.5, 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

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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.

Show:
© 2014 Microsoft