달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2016. 10. 12. 15:54

DateTime, TimeSpan 프로그래밍/C#2016. 10. 12. 15:54

DateTime Structure

https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx


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)

Syntax

[SerializableAttribute]
public struct DateTime : IComparable, IFormattable, IConvertible, 
	ISerializable, IComparable<DateTime>, IEquatable<DateTime>

Constructors

NameDescription
System_CAPS_pubmethodDateTime(Int32, Int32, Int32)

Initializes a new instance of the DateTime structure to the specified year, month, and day.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Calendar)

Initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar.

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32)

Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second.

System_CAPS_pubmethodDateTime(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.

System_CAPS_pubmethodDateTime(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.

System_CAPS_pubmethodDateTime(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.

System_CAPS_pubmethodDateTime(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.

System_CAPS_pubmethodDateTime(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.

System_CAPS_pubmethodDateTime(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.

System_CAPS_pubmethodDateTime(Int64)

Initializes a new instance of the DateTime structure to a specified number of ticks.

System_CAPS_pubmethodDateTime(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.

Properties

NameDescription
System_CAPS_pubpropertyDate

Gets the date component of this instance.

System_CAPS_pubpropertyDay

Gets the day of the month represented by this instance.

System_CAPS_pubpropertyDayOfWeek

Gets the day of the week represented by this instance.

System_CAPS_pubpropertyDayOfYear

Gets the day of the year represented by this instance.

System_CAPS_pubpropertyHour

Gets the hour component of the date represented by this instance.

System_CAPS_pubpropertyKind

Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.

System_CAPS_pubpropertyMillisecond

Gets the milliseconds component of the date represented by this instance.

System_CAPS_pubpropertyMinute

Gets the minute component of the date represented by this instance.

System_CAPS_pubpropertyMonth

Gets the month component of the date represented by this instance.

System_CAPS_pubpropertySystem_CAPS_staticNow

Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.

System_CAPS_pubpropertySecond

Gets the seconds component of the date represented by this instance.

System_CAPS_pubpropertyTicks

Gets the number of ticks that represent the date and time of this instance.

System_CAPS_pubpropertyTimeOfDay

Gets the time of day for this instance.

System_CAPS_pubpropertySystem_CAPS_staticToday

Gets the current date.

System_CAPS_pubpropertySystem_CAPS_staticUtcNow

Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).

System_CAPS_pubpropertyYear

Gets the year component of the date represented by this instance.

Methods

NameDescription
System_CAPS_pubmethodAdd(TimeSpan)

Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

System_CAPS_pubmethodAddDays(Double)

Returns a new DateTime that adds the specified number of days to the value of this instance.

System_CAPS_pubmethodAddHours(Double)

Returns a new DateTime that adds the specified number of hours to the value of this instance.

System_CAPS_pubmethodAddMilliseconds(Double)

Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.

System_CAPS_pubmethodAddMinutes(Double)

Returns a new DateTime that adds the specified number of minutes to the value of this instance.

System_CAPS_pubmethodAddMonths(Int32)

Returns a new DateTime that adds the specified number of months to the value of this instance.

System_CAPS_pubmethodAddSeconds(Double)

Returns a new DateTime that adds the specified number of seconds to the value of this instance.

System_CAPS_pubmethodAddTicks(Int64)

Returns a new DateTime that adds the specified number of ticks to the value of this instance.

System_CAPS_pubmethodAddYears(Int32)

Returns a new DateTime that adds the specified number of years to the value of this instance.

System_CAPS_pubmethodSystem_CAPS_staticCompare(DateTime, DateTime)

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.

System_CAPS_pubmethodCompareTo(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.

System_CAPS_pubmethodCompareTo(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.

System_CAPS_pubmethodSystem_CAPS_staticDaysInMonth(Int32, Int32)

Returns the number of days in the specified month and year.

System_CAPS_pubmethodEquals(DateTime)

Returns a value indicating whether the value of this instance is equal to the value of the specifiedDateTime instance.

System_CAPS_pubmethodSystem_CAPS_staticEquals(DateTime, DateTime)

Returns a value indicating whether two DateTime instances have the same date and time value.

System_CAPS_pubmethodEquals(Object)

Returns a value indicating whether this instance is equal to a specified object.(OverridesValueType.Equals(Object).)

System_CAPS_pubmethodSystem_CAPS_staticFromBinary(Int64)

Deserializes a 64-bit binary value and recreates an original serialized DateTime object.

System_CAPS_pubmethodSystem_CAPS_staticFromFileTime(Int64)

Converts the specified Windows file time to an equivalent local time.

System_CAPS_pubmethodSystem_CAPS_staticFromFileTimeUtc(Int64)

Converts the specified Windows file time to an equivalent UTC time.

System_CAPS_pubmethodSystem_CAPS_staticFromOADate(Double)

Returns a DateTime equivalent to the specified OLE Automation Date.

System_CAPS_pubmethodGetDateTimeFormats()

Converts the value of this instance to all the string representations supported by the standard date and time format specifiers.

System_CAPS_pubmethodGetDateTimeFormats(Char)

Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier.

System_CAPS_pubmethodGetDateTimeFormats(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.

System_CAPS_pubmethodGetDateTimeFormats(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.

System_CAPS_pubmethodGetHashCode()

Returns the hash code for this instance.(Overrides ValueType.GetHashCode().)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodGetTypeCode()

Returns the TypeCode for value type DateTime.

System_CAPS_pubmethodIsDaylightSavingTime()

Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone.

System_CAPS_pubmethodSystem_CAPS_staticIsLeapYear(Int32)

Returns an indication whether the specified year is a leap year.

System_CAPS_pubmethodSystem_CAPS_staticParse(String)

Converts the string representation of a date and time to its DateTime equivalent.

System_CAPS_pubmethodSystem_CAPS_staticParse(String, IFormatProvider)

Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

System_CAPS_pubmethodSystem_CAPS_staticParse(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.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(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.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(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.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(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.

System_CAPS_pubmethodSystem_CAPS_staticSpecifyKind(DateTime, DateTimeKind)

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.

System_CAPS_pubmethodSubtract(DateTime)

Subtracts the specified date and time from this instance.

System_CAPS_pubmethodSubtract(TimeSpan)

Subtracts the specified duration from this instance.

System_CAPS_pubmethodToBinary()

Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object.

System_CAPS_pubmethodToFileTime()

Converts the value of the current DateTime object to a Windows file time.

System_CAPS_pubmethodToFileTimeUtc()

Converts the value of the current DateTime object to a Windows file time.

System_CAPS_pubmethodToLocalTime()

Converts the value of the current DateTime object to local time.

System_CAPS_pubmethodToLongDateString()

Converts the value of the current DateTime object to its equivalent long date string representation.

System_CAPS_pubmethodToLongTimeString()

Converts the value of the current DateTime object to its equivalent long time string representation.

System_CAPS_pubmethodToOADate()

Converts the value of this instance to the equivalent OLE Automation date.

System_CAPS_pubmethodToShortDateString()

Converts the value of the current DateTime object to its equivalent short date string representation.

System_CAPS_pubmethodToShortTimeString()

Converts the value of the current DateTime object to its equivalent short time string representation.

System_CAPS_pubmethodToString()

Converts the value of the current DateTime object to its equivalent string representation using the formatting conventions of the current culture.(Overrides ValueType.ToString().)

System_CAPS_pubmethodToString(IFormatProvider)

Converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information.

System_CAPS_pubmethodToString(String)

Converts the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture.

System_CAPS_pubmethodToString(String, IFormatProvider)

Converts the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information.

System_CAPS_pubmethodToUniversalTime()

Converts the value of the current DateTime object to Coordinated Universal Time (UTC).

System_CAPS_pubmethodSystem_CAPS_staticTryParse(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.

System_CAPS_pubmethodSystem_CAPS_staticTryParse(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.

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(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.

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(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.

Fields

NameDescription
System_CAPS_pubfieldSystem_CAPS_staticMaxValue

Represents the largest possible value of DateTime. This field is read-only.

System_CAPS_pubfieldSystem_CAPS_staticMinValue

Represents the smallest possible value of DateTime. This field is read-only.

Operators

NameDescription
System_CAPS_puboperatorSystem_CAPS_staticAddition(DateTime, TimeSpan)

Adds a specified time interval to a specified date and time, yielding a new date and time.

System_CAPS_puboperatorSystem_CAPS_staticEquality(DateTime, DateTime)

Determines whether two specified instances of DateTime are equal.

System_CAPS_puboperatorSystem_CAPS_staticGreaterThan(DateTime, DateTime)

Determines whether one specified DateTime is later than another specified DateTime.

System_CAPS_puboperatorSystem_CAPS_staticGreaterThanOrEqual(DateTime, DateTime)

Determines whether one specified DateTime represents a date and time that is the same as or later than another specified DateTime.

System_CAPS_puboperatorSystem_CAPS_staticInequality(DateTime, DateTime)

Determines whether two specified instances of DateTime are not equal.

System_CAPS_puboperatorSystem_CAPS_staticLessThan(DateTime, DateTime)

Determines whether one specified DateTime is earlier than another specified DateTime.

System_CAPS_puboperatorSystem_CAPS_staticLessThanOrEqual(DateTime, DateTime)

Determines whether one specified DateTime represents a date and time that is the same as or earlier than another specified DateTime.

System_CAPS_puboperatorSystem_CAPS_staticSubtraction(DateTime, DateTime)

Subtracts a specified date and time from another specified date and time and returns a time interval.

System_CAPS_puboperatorSystem_CAPS_staticSubtraction(DateTime, TimeSpan)

Subtracts a specified time interval from a specified date and time and returns a new date and time.

Explicit Interface Implementations

NameDescription
System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToBoolean(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToByte(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToChar(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDateTime(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. Returns the current DateTime object.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDecimal(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDouble(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt16(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt32(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt64(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToSByte(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToSingle(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToType(Type, IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. Converts the current DateTime object to an object of a specified type.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt16(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt32(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt64(IFormatProvider)

This API supports the product infrastructure and is not intended to be used directly from your code. This conversion is not supported. Attempting to use this method throws anInvalidCastException.

System_CAPS_pubinterfaceSystem_CAPS_privmethodISerializable.GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo object with the data needed to serialize the current DateTimeobject.

Remarks

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

System_CAPS_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 theTimeSpan.TicksPerDayTimeSpan.TicksPerHourTimeSpan.TicksPerMinuteTimeSpan.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 aDateTime 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 resolution
DateTime vs. TimeSpan
DateTime values and calendars
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.

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

    DateTime date1 = DateTime.Now;
    DateTime date2 = DateTime.UtcNow;
    DateTime date3 = DateTime.Today;
    
  • By parsing the string representation of a date and time value. The ParseParseExactTryParse, 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.

    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 aDateTime variable declaration with no assignment in Visual Basic.

    DateTime dat1 = new DateTime();
    // The following method call displays 1/1/0001 12:00:00 AM.
    Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
    // The following method call displays True.
    Console.WriteLine(dat1.Equals(DateTime.MinValue));
    

DateTime values and their string representations

Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a DateTime value is the result of a formatting operation. Formatting is the process of converting a value to its string representation.

Because the appearance of date and time values is dependent on such factors as culture, international standards, application requirements, and personal preference, the DateTime structure offers a great deal of flexibility in formatting date and time values through the overloads of itsToString 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.

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.

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.

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.

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

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

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

      DateTime date1 = new DateTime(2013, 6, 1, 12, 32, 30);
      List<string> badFormats = new List<String>();

      Console.WriteLine("{0,-37} {1,-19}\n", "Date String", "Date");
      foreach (var dateString in date1.GetDateTimeFormats()) {
         DateTime parsedDate;
         if (DateTime.TryParse(dateString, out parsedDate))
            Console.WriteLine("{0,-37} {1,-19}", dateString, DateTime.Parse(dateString));
         else
            badFormats.Add(dateString);
      } 

      // Display strings that could not be parsed.
      if (badFormats.Count > 0) {
         Console.WriteLine("\nStrings that could not be parsed: ");
         foreach (var badFormat in badFormats)
            Console.WriteLine("   {0}", badFormat);         
      }
   }
}
// The example displays the following output:
//       Date String                           Date               
//       
//       01/06/2013                            01/06/2013 00:00:00
//       01/06/13                              01/06/2013 00:00:00
//       1/6/13                                01/06/2013 00:00:00
//       1.6.13                                01/06/2013 00:00:00
//       2013-06-01                            01/06/2013 00:00:00
//       01 June 2013                          01/06/2013 00:00:00
//       1 June 2013                           01/06/2013 00:00:00
//       01 June 2013 12:32                    01/06/2013 12:32:00
//       01 June 2013 12:32                    01/06/2013 12:32:00
//       01 June 2013 12:32 PM                 01/06/2013 12:32:00
//       01 June 2013 12:32 PM                 01/06/2013 12:32:00
//       1 June 2013 12:32                     01/06/2013 12:32:00
//       1 June 2013 12:32                     01/06/2013 12:32:00
//       1 June 2013 12:32 PM                  01/06/2013 12:32:00
//       1 June 2013 12:32 PM                  01/06/2013 12:32:00
//       01 June 2013 12:32:30                 01/06/2013 12:32:30
//       01 June 2013 12:32:30                 01/06/2013 12:32:30
//       01 June 2013 12:32:30 PM              01/06/2013 12:32:30
//       01 June 2013 12:32:30 PM              01/06/2013 12:32:30
//       1 June 2013 12:32:30                  01/06/2013 12:32:30
//       1 June 2013 12:32:30                  01/06/2013 12:32:30
//       1 June 2013 12:32:30 PM               01/06/2013 12:32:30
//       1 June 2013 12:32:30 PM               01/06/2013 12:32:30
//       01/06/2013 12:32                      01/06/2013 12:32:00
//       01/06/2013 12:32                      01/06/2013 12:32:00
//       01/06/2013 12:32 PM                   01/06/2013 12:32:00
//       01/06/2013 12:32 PM                   01/06/2013 12:32:00
//       01/06/13 12:32                        01/06/2013 12:32:00
//       01/06/13 12:32                        01/06/2013 12:32:00
//       01/06/13 12:32 PM                     01/06/2013 12:32:00
//       01/06/13 12:32 PM                     01/06/2013 12:32:00
//       1/6/13 12:32                          01/06/2013 12:32:00
//       1/6/13 12:32                          01/06/2013 12:32:00
//       1/6/13 12:32 PM                       01/06/2013 12:32:00
//       1/6/13 12:32 PM                       01/06/2013 12:32:00
//       1.6.13 12:32                          01/06/2013 12:32:00
//       1.6.13 12:32                          01/06/2013 12:32:00
//       1.6.13 12:32 PM                       01/06/2013 12:32:00
//       1.6.13 12:32 PM                       01/06/2013 12:32:00
//       2013-06-01 12:32                      01/06/2013 12:32:00
//       2013-06-01 12:32                      01/06/2013 12:32:00
//       2013-06-01 12:32 PM                   01/06/2013 12:32:00
//       2013-06-01 12:32 PM                   01/06/2013 12:32:00
//       01/06/2013 12:32:30                   01/06/2013 12:32:30
//       01/06/2013 12:32:30                   01/06/2013 12:32:30
//       01/06/2013 12:32:30 PM                01/06/2013 12:32:30
//       01/06/2013 12:32:30 PM                01/06/2013 12:32:30
//       01/06/13 12:32:30                     01/06/2013 12:32:30
//       01/06/13 12:32:30                     01/06/2013 12:32:30
//       01/06/13 12:32:30 PM                  01/06/2013 12:32:30
//       01/06/13 12:32:30 PM                  01/06/2013 12:32:30
//       1/6/13 12:32:30                       01/06/2013 12:32:30
//       1/6/13 12:32:30                       01/06/2013 12:32:30
//       1/6/13 12:32:30 PM                    01/06/2013 12:32:30
//       1/6/13 12:32:30 PM                    01/06/2013 12:32:30
//       1.6.13 12:32:30                       01/06/2013 12:32:30
//       1.6.13 12:32:30                       01/06/2013 12:32:30
//       1.6.13 12:32:30 PM                    01/06/2013 12:32:30
//       1.6.13 12:32:30 PM                    01/06/2013 12:32:30
//       2013-06-01 12:32:30                   01/06/2013 12:32:30
//       2013-06-01 12:32:30                   01/06/2013 12:32:30
//       2013-06-01 12:32:30 PM                01/06/2013 12:32:30
//       2013-06-01 12:32:30 PM                01/06/2013 12:32:30
//       01 June                               01/06/2013 00:00:00
//       01 June                               01/06/2013 00:00:00
//       2013-06-01T12:32:30.0000000           01/06/2013 12:32:30
//       2013-06-01T12:32:30.0000000           01/06/2013 12:32:30
//       Sat, 01 Jun 2013 12:32:30 GMT         01/06/2013 05:32:30
//       Sat, 01 Jun 2013 12:32:30 GMT         01/06/2013 05:32:30
//       2013-06-01T12:32:30                   01/06/2013 12:32:30
//       12:32                                 22/04/2013 12:32:00
//       12:32                                 22/04/2013 12:32:00
//       12:32 PM                              22/04/2013 12:32:00
//       12:32 PM                              22/04/2013 12:32:00
//       12:32:30                              22/04/2013 12:32:30
//       12:32:30                              22/04/2013 12:32:30
//       12:32:30 PM                           22/04/2013 12:32:30
//       12:32:30 PM                           22/04/2013 12:32:30
//       2013-06-01 12:32:30Z                  01/06/2013 05:32:30
//       01 June 2013 19:32:30                 01/06/2013 19:32:30
//       01 June 2013 19:32:30                 01/06/2013 19:32:30
//       01 June 2013 07:32:30 PM              01/06/2013 19:32:30
//       01 June 2013 7:32:30 PM               01/06/2013 19:32:30
//       1 June 2013 19:32:30                  01/06/2013 19:32:30
//       1 June 2013 19:32:30                  01/06/2013 19:32:30
//       1 June 2013 07:32:30 PM               01/06/2013 19:32:30
//       1 June 2013 7:32:30 PM                01/06/2013 19:32:30
//       June 2013                             01/06/2013 00:00:00
//       June 2013                             01/06/2013 00:00:00

You can use the TryParse and TryParseExact methods to convert a date and time string that must match a particular format or formats to aDateTime value. You specify the required format or formats as a parameter to the parsing methodby using one or more or 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.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] formats = { "yyyyMMdd", "HHmmss" };
      string[] dateStrings = { "20130816", "20131608", "  20130816   ", 
                               "115216", "521116", "  115216  " };
      DateTime parsedDate;

      foreach (var dateString in dateStrings) {
         if (DateTime.TryParseExact(dateString, formats, null, 
                                    DateTimeStyles.AllowWhiteSpaces |
                                    DateTimeStyles.AdjustToUniversal,
                                    out parsedDate))
            Console.WriteLine("{0} --> {1:g}", dateString, parsedDate);
         else
            Console.WriteLine("Cannot convert {0}", dateString);
      }
   }
}
// The example displays the following output:
//       20130816 --> 8/16/2013 12:00 AM
//       Cannot convert 20131608
//         20130816    --> 8/16/2013 12:00 AM
//       115216 --> 4/22/2013 11:52 AM
//       Cannot convert 521116
//         115216   --> 4/22/2013 11:52 AM

The Parse and ParseExact methods throw an exception if the string to be converted to a DateTime value cannot be parsed. The TryParse andTryParseExact 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 in the .NET Framework.

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.

System_CAPS_noteNote

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

System_CAPS_noteNote

As an alternative to performing date and time arithmetic on DateTime values to measure elapsed time, you can use the Stopwatch class.

The Ticks property expresses date and time values in units of one ten-millionth of a second, and the Millisecond property returns the thousandths of a second in a date and time value. However, if you are using repeated calls to the DateTime.Now property to measure elapsed time, and you are concerned with small time intervals less than 100 milliseconds, you should note that values returned by the DateTime.Now property are dependent on the system clock, which on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds.

The following example illustrates the dependence of current date and time values on the resolution of the system clock. In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. If the value of the outer loop counter is 10, a call to the Thread.Sleepmethod introduces a five millisecond delay. As the output from the example shows, the number of milliseconds in returned by theDateTime.Now.Milliseconds property changed only after the call to Thread.Sleep.

using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      String output = "";
      for (int ctr = 0; ctr <= 20; ctr++) {
         output += String.Format("{0}\n", DateTime.Now.Millisecond);
         // Introduce a delay loop.
         for (int delay = 0; delay <= 1000; delay++)
         {}

         if (ctr == 10) {
            output += "Thread.Sleep called...\n";
            Thread.Sleep(5);
         }
      }
      Console.WriteLine(output);
   }
}
// The example displays the following output:
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       Thread.Sleep called...
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143

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.

DateTime values and calendars

The .NET Framework Class Library includes a number of calendar classes, all of which are derived from the Calendar class. They are:

Each culture uses a default calendar defined by its read-only CultureInfo.Calendar property and supports one or more calendars defined by its read-only CultureInfo.OptionalCalendars property. The calendar currently used by a specific CultureInfo object is defined by itsDateTimeFormatInfo.Calendar property; it must be one of the calendars found in the CultureInfo.OptionalCalendars array.

A culture's current calendar is used in all formatting operations for that culture. For example, the default calendar of the Persian (Iran) culture is the Umm al-Qura calendar, which is represented by the UmAlQuraCalendar class. When a CultureInfo object that represents the Persian (Iran) culture is used in a date and time formatting operation, the Umm al-Qura calendar is used by default, and the Gregorian calendar is used only if the culture's DateTimeFormatInfo.Calendar property is changed, as the following example shows.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var value = new DateTime(2016, 5, 28);

      Console.WriteLine(value.ToString(faIR));

      faIR.DateTimeFormat.Calendar = new GregorianCalendar();
      Console.WriteLine(value.ToString(faIR));
   }
}
// The example displays the following output:
// 08/03/1395 12:00:00 ?.?
// 28/05/2016 12:00:00 ?.?

A culture's current calendar is also used in all parsing operations for that culture, as the following example shows.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var value = DateTime.Parse("08/03/1395", faIR);
      Console.WriteLine(value.ToString(faIR));

      faIR.DateTimeFormat.Calendar = new GregorianCalendar();
      Console.WriteLine(value.ToString(faIR));
   }
}
// The example displays the following output:
//       08/03/1395 12:00:00 ?.?
//       28/05/2016 12:00:00 ?.?

You can also instantiate a DateTime value by using the date and time elements (such as the number of the year, month, and day) of a specific calendar by calling a DateTime constructor that includes a calendar parameter and passing it a Calendar object that represents that calendar. The following example does this by using the date and time elements from the UmAlQuraCalendar calendar.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var dat = new DateTime(1395, 8, 18, faIR.DateTimeFormat.Calendar);
      Console.WriteLine("Umm-al-Qura date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Gregorian date:   {0:d}", dat);
   }
}
// The example displays the following output:
//       Umm-al-Qura date: 18/08/1395
//       Gregorian date:   11/8/2016

DateTime constructors that do not include a calendar parameter assume that the date and time elements are expressed as units in the Gregorian calendar.

All other DateTime properties and methods use the Gregorian calendar. For example, the DateTime.Year property returns the year in the Gregorian calendar, and the DateTime.IsLeapYear(Int32) method assumes that the year parameter is a year in the Gregorian calendar. Each DateTime member that uses the Gregorian calendar has a corresponding member of the Calendar class that uses a specific calendar. For example, theCalendar.GetYear method returns the year in a specific calendar, and the Calendar.IsLeapYear method interprets the year parameter as a year number in a specific calendar. The following example use both the DateTime and the corresponding members of the UmAlQuraCalendar class.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var cal = faIR.DateTimeFormat.Calendar;
      var dat = new DateTime(1395, 8, 18, cal);
      Console.WriteLine("Using the Umm-al-Qura calendar:");
      Console.WriteLine("Date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Year: {0}", cal.GetYear(dat));
      Console.WriteLine("Leap year: {0}\n", 
                        cal.IsLeapYear(cal.GetYear(dat)));

      Console.WriteLine("Using the Gregorian calendar:");
      Console.WriteLine("Date: {0:d}", dat);
      Console.WriteLine("Year: {0}", dat.Year);
      Console.WriteLine("Leap year: {0}", DateTime.IsLeapYear(dat.Year));
   }
}
// The example displays the following output:
//       Using the Umm-al-Qura calendar:
//       Date: 18/08/1395
//       Year: 1395
//       Leap year: True
//       
//       Using the Gregorian calendar:
//       Date: 11/8/2016
//       Year: 2016
//       Leap year: True

Although the DateTime structure includes DayOfWeek property that returns the day of the week in the Gregorian calendar, it does not include a member that allows you to retrieve the week number of the year. To retrieve the week of the year, call the individual calendar'sCalendar.GetWeekOfYear method. The following example provides an illustration.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var umAlQura = faIR.DateTimeFormat.Calendar;
      var dat = new DateTime(1395, 8, 18, umAlQura);
      Console.WriteLine("Using the Umm-al-Qura calendar:");
      Console.WriteLine("Date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Day of Week: {0}", umAlQura.GetDayOfWeek(dat));
      Console.WriteLine("Week of year: {0}\n", 
                        umAlQura.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, 
                                               DayOfWeek.Sunday));

      var greg = new GregorianCalendar(); 
      Console.WriteLine("Using the Gregorian calendar:");
      Console.WriteLine("Date: {0:d}", dat);
      Console.WriteLine("Day of Week: {0}", dat.DayOfWeek);
      Console.WriteLine("Week of year: {0}", 
                         greg.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, 
                                            DayOfWeek.Sunday));
   }
}
// The example displays the following output:
//       Using the Umm-al-Qura calendar:
//       Date: 18/08/1395
//       Day of Week: Tuesday
//       Week of year: 34
//       
//       Using the Gregorian calendar:
//       Date: 11/8/2016
//       Day of Week: Tuesday
//       Week of year: 46

For more information on dates and calendars, see Working with Calendars.

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 DateTimevalue represents a single instant of time, it should identify the same moment of time when it's restored.

Persisting values as strings

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

using System;
using System.Globalization;
using System.IO;
using System.Threading;

public class Example
{
   private const string filename = @".\BadDates.txt";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      string output = null;

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         output += dates[ctr].ToString() + (ctr != dates.Length - 1 ? "|" : "");
      }
      StreamWriter sw = new StreamWriter(filename);
      sw.Write(output);
      sw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      StreamReader sr = new StreamReader(filename);
      string[] inputValues = sr.ReadToEnd().Split( new char[] { '|' } , 
                                                  StringSplitOptions.RemoveEmptyEntries);
      sr.Close();
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var inputValue in inputValues) {
         DateTime dateValue;
         if (DateTime.TryParse(inputValue, out dateValue)) {
            Console.WriteLine("'{0}' --> {1:f}", inputValue, dateValue);
         }
         else {
            Console.WriteLine("Cannot parse '{0}'", inputValue);   
         }
      }
      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       Cannot parse //6/14/2014 6:32:00 AM//
//       //7/10/2014 11:49:00 PM// --> 07 October 2014 23:49
//       //1/10/2015 1:16:00 AM// --> 01 October 2015 01:16
//       Cannot parse //12/20/2014 9:45:00 PM//
//       //6/2/2014 3:14:00 PM// --> 06 February 2014 15:14
//       Restored dates...

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 theprovider argument. Specify that the value should round-trip by using the "O" or "R" .

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

using System;
using System.Globalization;
using System.IO;
using System.Threading;

public class Example
{
   private const string filename = @".\Dates.txt";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      string output = null;

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         output += dates[ctr].ToUniversalTime().ToString("O", CultureInfo.InvariantCulture) 
                   + (ctr != dates.Length - 1 ? "|" : "");
      }
      StreamWriter sw = new StreamWriter(filename);
      sw.Write(output);
      sw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      StreamReader sr = new StreamReader(filename);
      string[] inputValues = sr.ReadToEnd().Split( new char[] { '|' } , 
                                                  StringSplitOptions.RemoveEmptyEntries);
      sr.Close();
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var inputValue in inputValues) {
         DateTime dateValue;
         if (DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture, 
                               DateTimeStyles.RoundtripKind, out dateValue)) {
            Console.WriteLine("'{0}' --> {1:f}", 
                              inputValue, dateValue.ToLocalTime());
         }
         else {
            Console.WriteLine("Cannot parse '{0}'", inputValue);   
         }
      }
      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       '2014-06-14T13:32:00.0000000Z' --> 14 June 2014 14:32
//       '2014-07-11T06:49:00.0000000Z' --> 11 July 2014 07:49
//       '2015-01-10T09:16:00.0000000Z' --> 10 January 2015 09:16
//       '2014-12-21T05:45:00.0000000Z' --> 21 December 2014 05:45
//       '2014-06-02T22:14:00.0000000Z' --> 02 June 2014 23:14
//       Restored dates...

Persisting values as integers

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.

using System;
using System.Globalization;
using System.IO;
using System.Threading;

class Example
{
   private const string filename = @".\IntDates.bin";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      long[] ticks = new long[dates.Length];
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         ticks[ctr] = dates[ctr].ToUniversalTime().Ticks; 
      }
      FileStream fs = new FileStream(filename, FileMode.Create);
      BinaryWriter bw = new BinaryWriter(fs);
      bw.Write(ticks.Length);
      foreach (var tick in ticks)
         bw.Write(tick);

      bw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      FileStream fs = new FileStream(filename, FileMode.Open);
      BinaryReader br = new BinaryReader(fs);
      int items;
      DateTime[] dates;

      try { 
         items = br.ReadInt32();
         dates = new DateTime[items];

         for (int ctr = 0; ctr < items; ctr++) {
            long ticks = br.ReadInt64();
            dates[ctr] = new DateTime(ticks).ToLocalTime();
         }
      }   
      catch (EndOfStreamException) {
         Console.WriteLine("File corruption detected. Unable to restore data...");
         return;
      }   
      catch (IOException) {
         Console.WriteLine("Unspecified I/O error. Unable to restore data...");
         return;
      }
      // Thrown during array initialization.
      catch (OutOfMemoryException) {
         Console.WriteLine("File corruption detected. Unable to restore data...");
         return;
      }
      finally {      
         br.Close();
      }   

      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var value in dates)
         Console.WriteLine(value.ToString("f"));

      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       14 June 2014 14:32
//       11 July 2014 07:49
//       10 January 2015 09:16
//       21 December 2014 05:45
//       02 June 2014 23:14
//       Restored dates...

Serializing DateTime values

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

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.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Xml.Serialization;

class Example
{
   private const string filename = @".\LeapYears.xml";

   public static void Main()
   {
      // Serialize the data.
      List<DateTime> leapYears = new List<DateTime>();
      for (int year = 2000; year <= 2100; year += 4) {
         if (DateTime.IsLeapYear(year)) 
            leapYears.Add(new DateTime(year, 2, 29));
      }
      DateTime[] dateArray = leapYears.ToArray();

      XmlSerializer serializer = new XmlSerializer(dateArray.GetType());
      TextWriter sw = new StreamWriter(filename);

      try {
         serializer.Serialize(sw, dateArray);
      }
      catch (InvalidOperationException e) {
         Console.WriteLine(e.InnerException.Message);         
      }
      finally {
         if (sw != null) sw.Close();
      }   

      // Deserialize the data.
      DateTime[] deserializedDates;
      using (FileStream fs = new FileStream(filename, FileMode.Open)) {
         deserializedDates = (DateTime[]) serializer.Deserialize(fs);
      } 

      // Display the dates.
      Console.WriteLine("Leap year days from 2000-2100 on an {0} system:",
                        Thread.CurrentThread.CurrentCulture.Name);
      int nItems = 0;
      foreach (var dat in deserializedDates) {
         Console.Write("   {0:d}     ", dat);
         nItems++;
         if (nItems % 5 == 0) 
               Console.WriteLine(); 
      }
   }
}
// The example displays the following output:
//    Leap year days from 2000-2100 on an en-GB system:
//       29/02/2000       29/02/2004       29/02/2008       29/02/2012       29/02/2016
//       29/02/2020       29/02/2024       29/02/2028       29/02/2032       29/02/2036
//       29/02/2040       29/02/2044       29/02/2048       29/02/2052       29/02/2056
//       29/02/2060       29/02/2064       29/02/2068       29/02/2072       29/02/2076
//       29/02/2080       29/02/2084       29/02/2088       29/02/2092       29/02/2096

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 serializeDateTime data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the UTC zone.

using System;
using System.IO;
using System.Globalization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

class Example
{
   private const string filename = @".\Dates.bin";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      FileStream fs = new FileStream(filename, FileMode.Create);
      BinaryFormatter bin = new BinaryFormatter();

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         dates[ctr] = dates[ctr].ToUniversalTime();
      }
      bin.Serialize(fs, dates);
      fs.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

      FileStream fs = new FileStream(filename, FileMode.Open);
      BinaryFormatter bin = new BinaryFormatter();
      DateTime[] dates = (DateTime[]) bin.Deserialize(fs);
      fs.Close();

      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var value in dates)
         Console.WriteLine(value.ToLocalTime().ToString("f"));

      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       14 June 2014 14:32
//       11 July 2014 07:49
//       10 January 2015 09:16
//       21 December 2014 05:45
//       02 June 2014 23:14
//       Restored dates...

Serializing DateTime and time zone data

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 theDateTimevalue and the TimeZoneInfo object that represents its time zone. To do this, create a type whose fields include both the DateTimevalue and its time zone. The following example defines a DateWithTimeZone structure that illustrates how this might be done.

using System;

namespace DateTimeExtensions
{
   [Serializable] public struct DateWithTimeZone
   {
      private TimeZoneInfo tz;
      private DateTime dt;

      public DateWithTimeZone(DateTime dateValue, TimeZoneInfo timeZone)
      {
         dt = dateValue;
         if (timeZone == null)
            tz = TimeZoneInfo.Local;
         else
            tz = timeZone;
      }   

      public TimeZoneInfo TimeZone 
      { get { return (tz); }
        set { tz = value; } }

      public DateTime DateTime 
      { get { return (dt); }
        set { dt = value; } }
   }
}
System_CAPS_importantImportant

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

using System;
using DateTimeExtensions;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Example
{
   public static void Main()
   {
      DateWithTimeZone[] dates= { new DateWithTimeZone(new DateTime(2014, 8, 9, 19, 30, 0),  
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
                                  new DateWithTimeZone(new DateTime(2014, 8, 15, 19, 0, 0), 
                                      TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")),  
                                  new DateWithTimeZone(new DateTime(2014, 8, 22, 19, 30, 0),  
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),  
                                  new DateWithTimeZone(new DateTime(2014, 8, 28, 19, 0, 0), 
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")) };
      FileStream fs = new FileStream(@".\Schedule.bin", FileMode.Create);
      BinaryFormatter formatter = new BinaryFormatter();
      try {
         formatter.Serialize(fs, dates);
         // Display dates.
         foreach (var date in dates) {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine("{0} {1}", date.DateTime, 
                              tz.IsDaylightSavingTime(date.DateTime) ? 
                              tz.DaylightName : tz.StandardName);      
         }
      }
      catch (SerializationException e) {
         Console.WriteLine("Serialization failed. Reason: {0}", e.Message);
      }   
      finally {
         if (fs != null) fs.Close();
      }
   }
}
// The example displays the following output:
//       8/9/2014 7:30:00 PM Eastern Daylight Time
//       8/15/2014 7:00:00 PM Pacific Daylight Time
//       8/22/2014 7:30:00 PM Eastern Daylight Time
//       8/28/2014 7:00:00 PM Eastern Daylight Time

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

using System;
using DateTimeExtensions;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Example
{
   private const string filename = @".\Schedule.bin";

   public static void Main()
   {
      FileStream fs;
      if (File.Exists(filename))
         fs = new FileStream(filename, FileMode.Open);
      else {
         Console.WriteLine("Unable to find file to deserialize.");
         return;
      }

      BinaryFormatter formatter = new BinaryFormatter();
      DateWithTimeZone[] dates;
      try {
         dates = (DateWithTimeZone[]) formatter.Deserialize(fs);
         // Display dates.
         foreach (var date in dates) {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine("{0} {1}", date.DateTime, 
                              tz.IsDaylightSavingTime(date.DateTime) ? 
                              tz.DaylightName : tz.StandardName);      
         }
      }
      catch (SerializationException e) {
         Console.WriteLine("Deserialization failed. Reason: {0}", e.Message);
      }   
      finally {
         if (fs != null) fs.Close();
      }
   }
}
// The example displays the following output:
//       8/9/2014 7:30:00 PM Eastern Daylight Time
//       8/15/2014 7:00:00 PM Pacific Daylight Time
//       8/22/2014 7:30:00 PM Eastern Daylight Time
//       8/28/2014 7:00:00 PM Eastern Daylight Time

COM interop considerations

DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. However, aDateTime 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.

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

Version Information

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

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.

System_CAPS_cautionCaution

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.




TimeSpan Structure

https://msdn.microsoft.com/en-us/library/system.timespan(v=vs.110).aspx


Represents a time interval.

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

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

Syntax

[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct TimeSpan : IComparable, IComparable<TimeSpan>, 
	IEquatable<TimeSpan>, IFormattable

Constructors

NameDescription
System_CAPS_pubmethodTimeSpan(Int32, Int32, Int32)

Initializes a new instance of the TimeSpan structure to a specified number of hours, minutes, and seconds.

System_CAPS_pubmethodTimeSpan(Int32, Int32, Int32, Int32)

Initializes a new instance of the TimeSpan structure to a specified number of days, hours, minutes, and seconds.

System_CAPS_pubmethodTimeSpan(Int32, Int32, Int32, Int32, Int32)

Initializes a new instance of the TimeSpan structure to a specified number of days, hours, minutes, seconds, and milliseconds.

System_CAPS_pubmethodTimeSpan(Int64)

Initializes a new instance of the TimeSpan structure to the specified number of ticks.

Properties

NameDescription
System_CAPS_pubpropertyDays

Gets the days component of the time interval represented by the current TimeSpan structure.

System_CAPS_pubpropertyHours

Gets the hours component of the time interval represented by the current TimeSpan structure.

System_CAPS_pubpropertyMilliseconds

Gets the milliseconds component of the time interval represented by the current TimeSpan structure.

System_CAPS_pubpropertyMinutes

Gets the minutes component of the time interval represented by the current TimeSpan structure.

System_CAPS_pubpropertySeconds

Gets the seconds component of the time interval represented by the current TimeSpan structure.

System_CAPS_pubpropertyTicks

Gets the number of ticks that represent the value of the current TimeSpan structure.

System_CAPS_pubpropertyTotalDays

Gets the value of the current TimeSpan structure expressed in whole and fractional days.

System_CAPS_pubpropertyTotalHours

Gets the value of the current TimeSpan structure expressed in whole and fractional hours.

System_CAPS_pubpropertyTotalMilliseconds

Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.

System_CAPS_pubpropertyTotalMinutes

Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

System_CAPS_pubpropertyTotalSeconds

Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.

Methods

NameDescription
System_CAPS_pubmethodAdd(TimeSpan)

Returns a new TimeSpan object whose value is the sum of the specified TimeSpan object and this instance.

System_CAPS_pubmethodSystem_CAPS_staticCompare(TimeSpan, TimeSpan)

Compares two TimeSpan values and returns an integer that indicates whether the first value is shorter than, equal to, or longer than the second value.

System_CAPS_pubmethodCompareTo(Object)

Compares this instance to a specified object and returns an integer that indicates whether this instance is shorter than, equal to, or longer than the specified object.

System_CAPS_pubmethodCompareTo(TimeSpan)

Compares this instance to a specified TimeSpan object and returns an integer that indicates whether this instance is shorter than, equal to, or longer than the TimeSpan object.

System_CAPS_pubmethodDuration()

Returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object.

System_CAPS_pubmethodEquals(Object)

Returns a value indicating whether this instance is equal to a specified object.(OverridesValueType.Equals(Object).)

System_CAPS_pubmethodEquals(TimeSpan)

Returns a value indicating whether this instance is equal to a specified TimeSpan object.

System_CAPS_pubmethodSystem_CAPS_staticEquals(TimeSpan, TimeSpan)

Returns a value that indicates whether two specified instances of TimeSpan are equal.

System_CAPS_pubmethodSystem_CAPS_staticFromDays(Double)

Returns a TimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond.

System_CAPS_pubmethodSystem_CAPS_staticFromHours(Double)

Returns a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.

System_CAPS_pubmethodSystem_CAPS_staticFromMilliseconds(Double)

Returns a TimeSpan that represents a specified number of milliseconds.

System_CAPS_pubmethodSystem_CAPS_staticFromMinutes(Double)

Returns a TimeSpan that represents a specified number of minutes, where the specification is accurate to the nearest millisecond.

System_CAPS_pubmethodSystem_CAPS_staticFromSeconds(Double)

Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.

System_CAPS_pubmethodSystem_CAPS_staticFromTicks(Int64)

Returns a TimeSpan that represents a specified time, where the specification is in units of ticks.

System_CAPS_pubmethodGetHashCode()

Returns a hash code for this instance.(Overrides ValueType.GetHashCode().)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodNegate()

Returns a new TimeSpan object whose value is the negated value of this instance.

System_CAPS_pubmethodSystem_CAPS_staticParse(String)

Converts the string representation of a time interval to its TimeSpan equivalent.

System_CAPS_pubmethodSystem_CAPS_staticParse(String, IFormatProvider)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String, IFormatProvider)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String, IFormatProvider, TimeSpanStyles)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified format, culture-specific format information, and styles. The format of the string representation must match the specified format exactly.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String[], IFormatProvider)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified array of format strings and culture-specific format information. The format of the string representation must match one of the specified formats exactly.

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String[], IFormatProvider, TimeSpanStyles)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified formats, culture-specific format information, and styles. The format of the string representation must match one of the specified formats exactly.

System_CAPS_pubmethodSubtract(TimeSpan)

Returns a new TimeSpan object whose value is the difference between the specified TimeSpan object and this instance.

System_CAPS_pubmethodToString()

Converts the value of the current TimeSpan object to its equivalent string representation.(OverridesValueType.ToString().)

System_CAPS_pubmethodToString(String)

Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format.

System_CAPS_pubmethodToString(String, IFormatProvider)

Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format and culture-specific formatting information.

System_CAPS_pubmethodSystem_CAPS_staticTryParse(String, IFormatProvider, TimeSpan)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific formatting information, and returns a value that indicates whether the conversion succeeded.

System_CAPS_pubmethodSystem_CAPS_staticTryParse(String, TimeSpan)

Converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(String, String, IFormatProvider, TimeSpan)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified format and culture-specific format information, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match the specified format exactly.

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan)

Converts the string representation of a time interval to its TimeSpan equivalent by using the specified format, culture-specific format information, and styles, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match the specified format exactly.

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(String, String[], IFormatProvider, TimeSpan)

Converts the specified string representation of a time interval to its TimeSpan equivalent by using the specified formats and culture-specific format information, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match one of the specified formats exactly.

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan)

Converts the specified string representation of a time interval to its TimeSpan equivalent by using the specified formats, culture-specific format information, and styles, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match one of the specified formats exactly.

Fields

NameDescription
System_CAPS_pubfieldSystem_CAPS_staticMaxValue

Represents the maximum TimeSpan value. This field is read-only.

System_CAPS_pubfieldSystem_CAPS_staticMinValue

Represents the minimum TimeSpan value. This field is read-only.

System_CAPS_pubfieldSystem_CAPS_staticTicksPerDay

Represents the number of ticks in 1 day. This field is constant.

System_CAPS_pubfieldSystem_CAPS_staticTicksPerHour

Represents the number of ticks in 1 hour. This field is constant.

System_CAPS_pubfieldSystem_CAPS_staticTicksPerMillisecond

Represents the number of ticks in 1 millisecond. This field is constant.

System_CAPS_pubfieldSystem_CAPS_staticTicksPerMinute

Represents the number of ticks in 1 minute. This field is constant.

System_CAPS_pubfieldSystem_CAPS_staticTicksPerSecond

Represents the number of ticks in 1 second.

System_CAPS_pubfieldSystem_CAPS_staticZero

Represents the zero TimeSpan value. This field is read-only.

Operators

NameDescription
System_CAPS_puboperatorSystem_CAPS_staticAddition(TimeSpan, TimeSpan)

Adds two specified TimeSpan instances.

System_CAPS_puboperatorSystem_CAPS_staticEquality(TimeSpan, TimeSpan)

Indicates whether two TimeSpan instances are equal.

System_CAPS_puboperatorSystem_CAPS_staticGreaterThan(TimeSpan, TimeSpan)

Indicates whether a specified TimeSpan is greater than another specified TimeSpan.

System_CAPS_puboperatorSystem_CAPS_staticGreaterThanOrEqual(TimeSpan, TimeSpan)

Indicates whether a specified TimeSpan is greater than or equal to another specifiedTimeSpan.

System_CAPS_puboperatorSystem_CAPS_staticInequality(TimeSpan, TimeSpan)

Indicates whether two TimeSpan instances are not equal.

System_CAPS_puboperatorSystem_CAPS_staticLessThan(TimeSpan, TimeSpan)

Indicates whether a specified TimeSpan is less than another specified TimeSpan.

System_CAPS_puboperatorSystem_CAPS_staticLessThanOrEqual(TimeSpan, TimeSpan)

Indicates whether a specified TimeSpan is less than or equal to another specifiedTimeSpan.

System_CAPS_puboperatorSystem_CAPS_staticSubtraction(TimeSpan, TimeSpan)

Subtracts a specified TimeSpan from another specified TimeSpan.

System_CAPS_puboperatorSystem_CAPS_staticUnaryNegation(TimeSpan)

Returns a TimeSpan whose value is the negated value of the specified instance.

System_CAPS_puboperatorSystem_CAPS_staticUnaryPlus(TimeSpan)

Returns the specified instance of TimeSpan.

Remarks

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

TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead. (For more information about using the TimeSpanstructure to reflect the time of day, see Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo.)

System_CAPS_noteNote

TimeSpan value represents a time interval and can be expressed as a particular number of days, hours, minutes, seconds, and milliseconds. Because it represents a general interval without reference to a particular start or end point, it cannot be expressed in terms of years and months, both of which have a variable number of days. It differs from a DateTime value, which represents a date and time without reference to a particular time zone, or a DateTimeOffset value, which represents a specific moment of time.

The largest unit of time that the TimeSpan structure uses to measure duration is a day. Time intervals are measured in days for consistency, because the number of days in larger units of time, such as months and years, varies.

The value of a TimeSpan object is the number of ticks that equal the represented time interval. A tick is equal to 100 nanoseconds, or one ten-millionth of a second. The value of a TimeSpan object can range from TimeSpan.MinValue to TimeSpan.MaxValue.

Instantiating a TimeSpan Value

You can instantiate a TimeSpan value in a number of ways:

  • By calling its implicit default constructor. This creates an object whose value is TimeSpan.Zero, as the following example shows.

    TimeSpan interval = new TimeSpan();
    Console.WriteLine(interval.Equals(TimeSpan.Zero));    // Displays "True".
    
  • By calling one of its explicit constructors. The following example initializes a TimeSpan value to a specified number of hours, minutes, and seconds.

    TimeSpan interval = new TimeSpan(2, 14, 18);
    Console.WriteLine(interval.ToString());              // Displays "02:14:18".
    
  • By calling a method or performing an operation that returns a TimeSpan value. For example, you can instantiate a TimeSpan value that represents the interval between two date and time values, as the following example shows.

    DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
    DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
    TimeSpan travelTime = arrival - departure;  
    Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime);      
    // The example displays the following output:
    //       6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00
    

    You can also initialize a TimeSpan object to a zero time value in this way, as the following example shows.

    using System;
    
    public class Example
    {
       static Random rnd = new Random();
    
       public static void Main()
       {
          TimeSpan timeSpent = TimeSpan.Zero;
    
          timeSpent += GetTimeBeforeLunch();
          timeSpent += GetTimeAfterLunch();
    
          Console.WriteLine("Total time: {0}", timeSpent);
       }
    
       private static TimeSpan GetTimeBeforeLunch()
       {
          return new TimeSpan(rnd.Next(3, 6), 0, 0);
       }
    
       private static TimeSpan GetTimeAfterLunch()
       {
          return new TimeSpan(rnd.Next(3, 6), 0, 0);
       }
    }
    // The example displays output like the following:
    //        Total time: 08:00:00
    

    TimeSpan values are returned by arithmetic operators and methods of the DateTimeDateTimeOffset, and TimeSpan structures.

  • By parsing the string representation of a TimeSpan value. You can use the Parse and TryParse methods to convert strings that contain time intervals to TimeSpan values. The following example uses the Parse method to convert an array of strings to TimeSpan values.

    string[] values = { "12", "31.", "5.8:32:16", "12:12:15.95", ".12"};
    foreach (string value in values)
    {
       try {
          TimeSpan ts = TimeSpan.Parse(value);
          Console.WriteLine("'{0}' --> {1}", value, ts);
       }
       catch (FormatException) {
          Console.WriteLine("Unable to parse '{0}'", value);
       }
       catch (OverflowException) {
          Console.WriteLine("'{0}' is outside the range of a TimeSpan.", value);
       }   
    }
    // The example displays the following output:
    //       '12' --> 12.00:00:00
    //       Unable to parse '31.'
    //       '5.8:32:16' --> 5.08:32:16
    //       '12:12:15.95' --> 12:12:15.9500000
    //       Unable to parse '.12'  
    

    In addition, you can define the precise format of the input string to be parsed and converted to a TimeSpan value by calling the ParseExactor TryParseExact method.

Performing Operations on TimeSpan Values

You can add and subtract time durations either by using the Addition and Subtraction operators, or by calling the Add and Subtract methods. You can also compare two time durations by calling the CompareCompareTo, and Equals methods. The TimeSpan structure also includes the Durationand Negate methods, which convert time intervals to positive and negative values,

The range of TimeSpan values is MinValue to MaxValue.

Formatting a TimeSpan Value

TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. That is, a time interval consists of a positive or negative number of days without a time of day, or a number of days with a time of day, or only a time of day.

Beginning with the .NET Framework 4, the TimeSpan structure supports culture-sensitive formatting through the overloads of its ToString method, which converts a TimeSpan value to its string representation. The default TimeSpan.ToString() method returns a time interval by using an invariant format that is identical to its return value in previous versions of the .NET Framework. The TimeSpan.ToString(String) overload lets you specify a format string that defines the string representation of the time interval. The TimeSpan.ToString(String, IFormatProvider) overload lets you specify a format string and the culture whose formatting conventions are used to create the string representation of the time interval. TimeSpan supports both standard and custom format strings. (For more information, see Standard TimeSpan Format Strings and Custom TimeSpan Format Strings.) However, only standard format strings are culture-sensitive.

Restoring Legacy TimeSpan Formatting

In some cases, code that successfully formats TimeSpan values in .NET Framework 3.5 and earlier versions fails in .NET Framework 4. This is most common in code that calls a <TimeSpan_LegacyFormatMode> element method to format a TimeSpan value with a format string. The following example successfully formats a TimeSpan value in .NET Framework 3.5 and earlier versions, but throws an exception in .NET Framework 4 and later versions. Note that it attempts to format a TimeSpan value by using an unsupported format specifier, which is ignored in .NET Framework 3.5 and earlier versions.

TimeSpan interval = new TimeSpan(12, 30, 45);
string output;
try {
   output = String.Format("{0:r}", interval);
}
catch (FormatException) {
   output = "Invalid Format";
}
Console.WriteLine(output);
// Output from .NET Framework 3.5 and earlier versions:
//       12:30:45
// Output from .NET Framework 4:
//       Invalid Format

If you cannot modify the code, you can restore the legacy formatting of TimeSpan values in one of the following ways:

  • By creating a configuration file that contains the <TimeSpan_LegacyFormatMode> element. Setting this element's enabled attribute totrue restores legacy TimeSpan formatting on a per-application basis.

  • By setting the "NetFx40_TimeSpanLegacyFormatMode" compatibility switch when you create an application domain. This enables legacyTimeSpan formatting on a per-application-domain basis. The following example creates an application domain that uses legacy TimeSpanformatting.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          AppDomainSetup appSetup = new AppDomainSetup();
          appSetup.SetCompatibilitySwitches( new string[] { "NetFx40_TimeSpanLegacyFormatMode" } );
          AppDomain legacyDomain = AppDomain.CreateDomain("legacyDomain", 
                                                          null, appSetup);
          legacyDomain.ExecuteAssembly("ShowTimeSpan.exe");
       }
    }
    

    When the following code executes in the new application domain, it reverts to legacy TimeSpan formatting behavior.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          TimeSpan interval = DateTime.Now - DateTime.Now.Date;
          string msg = String.Format("Elapsed Time Today: {0:d} hours.",
                                     interval);
          Console.WriteLine(msg);
       }
    }
    // The example displays the following output:
    //       Elapsed Time Today: 01:40:52.2524662 hours.
    

Examples

The following example instantiates a TimeSpan object that represents the difference between two dates. It then displays the TimeSpan object's properties.

// Define two dates.
DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15);
DateTime date2 = new DateTime(2010, 8, 18, 13, 30, 30);
// Calculate the interval between the two dates.
TimeSpan interval = date2 - date1;
Console.WriteLine("{0} - {1} = {2}", date2, date1, interval.ToString());
// Display individual properties of the resulting TimeSpan object.
Console.WriteLine("   {0,-35} {1,20}", "Value of Days Component:", interval.Days);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Days:", interval.TotalDays);
Console.WriteLine("   {0,-35} {1,20}", "Value of Hours Component:", interval.Hours);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Hours:", interval.TotalHours);
Console.WriteLine("   {0,-35} {1,20}", "Value of Minutes Component:", interval.Minutes);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Minutes:", interval.TotalMinutes);
Console.WriteLine("   {0,-35} {1,20:N0}", "Value of Seconds Component:", interval.Seconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Total Number of Seconds:", interval.TotalSeconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Value of Milliseconds Component:", interval.Milliseconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Total Number of Milliseconds:", interval.TotalMilliseconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Ticks:", interval.Ticks);
// the example displays the following output:
//       8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15
//          Value of Days Component:                             229
//          Total Number of Days:                   229.229340277778
//          Value of Hours Component:                              5
//          Total Number of Hours:                  5501.50416666667
//          Value of Minutes Component:                           30
//          Total Number of Minutes:                       330090.25
//          Value of Seconds Component:                           15
//          Total Number of Seconds:                      19,805,415
//          Value of Milliseconds Component:                       0
//          Total Number of Milliseconds:             19,805,415,000
//          Ticks:                               198,054,150,000,000

Version Information

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

Thread Safety

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




'프로그래밍 > C#' 카테고리의 다른 글

IEnumerable Interface  (0) 2016.11.14
Predicate<T> Delegate  (0) 2016.10.18
C# 코딩 규칙  (0) 2016.08.28
예외 및 예외 처리  (0) 2016.08.26
파일 시스템 및 레지스트리  (0) 2016.08.25
:
Posted by 지훈2