The Labs \ Source Viewer \ SSCLI \ System \ DateTime

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. namespace System
  16. {
  17.    
  18.     using System;
  19.     using System.Threading;
  20.     using System.Globalization;
  21.     using System.Runtime.InteropServices;
  22.     using System.Runtime.CompilerServices;
  23.     using System.Runtime.Serialization;
  24.     using System.Security.Permissions;
  25.     using CultureInfo = System.Globalization.CultureInfo;
  26.     using Calendar = System.Globalization.Calendar;
  27.    
  28.     // This value type represents a date and time. Every DateTime
  29.     // object has a private field (Ticks) of type Int64 that stores the
  30.     // date and time as the number of 100 nanosecond intervals since
  31.     // 12:00 AM January 1, year 1 A.D. in the proleptic Gregorian Calendar.
  32.     //
  33.     // Starting from V2.0, DateTime also stored some context about its time
  34.     // zone in the form of a 3-state value representing Unspecified, Utc or
  35.     // Local. This is stored in the two top bits of the 64-bit numeric value
  36.     // with the remainder of the bits storing the tick count. This information
  37.     // is only used during time zone conversions and is not part of the
  38.     // identity of the DateTime. Thus, operations like Compare and Equals
  39.     // ignore this state. This is to stay compatible with earlier behavior
  40.     // and performance characteristics and to avoid forcing people into dealing
  41.     // with the effects of daylight savings. Note, that this has little effect
  42.     // on how the DateTime works except in a context where its specific time
  43.     // zone is needed, such as during conversions and some parsing and formatting
  44.     // cases.
  45.     //
  46.     // There is also 4th state stored that is a special type of Local value that
  47.     // is used to avoid data loss when round-tripping between local and UTC time.
  48.     // See below for more information on this 4th state, although it is
  49.     // effectively hidden from most users, who just see the 3-state DateTimeKind
  50.     // enumeration.
  51.     //
  52.     // For compatability, DateTime does not serialize the Kind data when used in
  53.     // binary serialization.
  54.     //
  55.     // For a description of various calendar issues, look at
  56.     //
  57.     // Calendar Studies web site, at
  58.     // http://serendipity.nofadz.com/hermetic/cal_stud.htm.
  59.     //
  60.     //
  61.     [StructLayout(LayoutKind.Auto)]
  62.     [Serializable()]
  63.     public struct DateTime : IComparable, IFormattable, IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>
  64.     {
  65.        
  66.         // Number of 100ns ticks per time unit
  67.         private const long TicksPerMillisecond = 10000;
  68.         private const long TicksPerSecond = TicksPerMillisecond * 1000;
  69.         private const long TicksPerMinute = TicksPerSecond * 60;
  70.         private const long TicksPerHour = TicksPerMinute * 60;
  71.         private const long TicksPerDay = TicksPerHour * 24;
  72.        
  73.         // Number of milliseconds per time unit
  74.         private const int MillisPerSecond = 1000;
  75.         private const int MillisPerMinute = MillisPerSecond * 60;
  76.         private const int MillisPerHour = MillisPerMinute * 60;
  77.         private const int MillisPerDay = MillisPerHour * 24;
  78.        
  79.         // Number of days in a non-leap year
  80.         private const int DaysPerYear = 365;
  81.         // Number of days in 4 years
  82.         private const int DaysPer4Years = DaysPerYear * 4 + 1;
  83.         // Number of days in 100 years
  84.         private const int DaysPer100Years = DaysPer4Years * 25 - 1;
  85.         // Number of days in 400 years
  86.         private const int DaysPer400Years = DaysPer100Years * 4 + 1;
  87.        
  88.         // Number of days from 1/1/0001 to 12/31/1600
  89.         private const int DaysTo1601 = DaysPer400Years * 4;
  90.         // Number of days from 1/1/0001 to 12/30/1899
  91.         private const int DaysTo1899 = DaysPer400Years * 4 + DaysPer100Years * 3 - 367;
  92.         // Number of days from 1/1/0001 to 12/31/9999
  93.         private const int DaysTo10000 = DaysPer400Years * 25 - 366;
  94.        
  95.         internal const long MinTicks = 0;
  96.         internal const long MaxTicks = DaysTo10000 * TicksPerDay - 1;
  97.         private const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
  98.        
  99.         private const long FileTimeOffset = DaysTo1601 * TicksPerDay;
  100.         private const long DoubleDateOffset = DaysTo1899 * TicksPerDay;
  101.         // The minimum OA date is 0100/01/01 (Note it's year 100).
  102.         // The maximum OA date is 9999/12/31
  103.         private const long OADateMinAsTicks = (DaysPer100Years - DaysPerYear) * TicksPerDay;
  104.         // All OA dates must be greater than (not >=) OADateMinAsDouble
  105.         private const double OADateMinAsDouble = -657435.0;
  106.         // All OA dates must be less than (not <=) OADateMaxAsDouble
  107.         private const double OADateMaxAsDouble = 2958466.0;
  108.        
  109.         private const int DatePartYear = 0;
  110.         private const int DatePartDayOfYear = 1;
  111.         private const int DatePartMonth = 2;
  112.         private const int DatePartDay = 3;
  113.        
  114.         private static readonly int[] DaysToMonth365 = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273,
  115.         304, 334, 365};
  116.         private static readonly int[] DaysToMonth366 = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274,
  117.         305, 335, 366};
  118.        
  119.         public static readonly DateTime MinValue = new DateTime(MinTicks, DateTimeKind.Unspecified);
  120.         public static readonly DateTime MaxValue = new DateTime(MaxTicks, DateTimeKind.Unspecified);
  121.        
  122.         private const UInt64 TicksMask = 4611686018427387903l;
  123.         private const UInt64 FlagsMask = 13835058055282163712ul;
  124.         private const UInt64 LocalMask = 9223372036854775808ul;
  125.         private const Int64 TicksCeiling = 4611686018427387904l;
  126.         private const UInt64 KindUnspecified = 0;
  127.         private const UInt64 KindUtc = 4611686018427387904l;
  128.         private const UInt64 KindLocal = 9223372036854775808ul;
  129.         private const UInt64 KindLocalAmbiguousDst = 13835058055282163712ul;
  130.         private const Int32 KindShift = 62;
  131.        
  132.         private const string TicksField = "ticks";
  133.         private const string DateDataField = "dateData";
  134.        
  135.         // The data is stored as an unsigned 64-bit integeter
  136.         // Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value
  137.         // 12/31/9999 23:59:59.9999999
  138.         // Bits 63-64: A four-state value that describes the DateTimeKind value of the date time, with a 2nd
  139.         // value for the rare case where the date time is local, but is in an overlapped daylight
  140.         // savings time hour and it is in daylight savings time. This allows distinction of these
  141.         // otherwise ambiguous local times and prevents data loss when round tripping from Local to
  142.         // UTC time.
  143.         private UInt64 dateData;
  144.        
  145.         // Constructs a DateTime from a tick count. The ticks
  146.         // argument specifies the date as the number of 100-nanosecond intervals
  147.         // that have elapsed since 1/1/0001 12:00am.
  148.         //
  149.         public DateTime(long ticks)
  150.         {
  151.             if (ticks < MinTicks || ticks > MaxTicks)
  152.                 throw new ArgumentOutOfRangeException("ticks", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
  153.             dateData = (UInt64)ticks;
  154.         }
  155.        
  156.         private DateTime(UInt64 dateData)
  157.         {
  158.             this.dateData = dateData;
  159.         }
  160.        
  161.         public DateTime(long ticks, DateTimeKind kind)
  162.         {
  163.             if (ticks < MinTicks || ticks > MaxTicks) {
  164.                 throw new ArgumentOutOfRangeException("ticks", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
  165.             }
  166.             if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
  167.                 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), "kind");
  168.             }
  169.             this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
  170.         }
  171.        
  172.         internal DateTime(long ticks, DateTimeKind kind, bool isAmbiguousDst)
  173.         {
  174.             if (ticks < MinTicks || ticks > MaxTicks) {
  175.                 throw new ArgumentOutOfRangeException("ticks", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
  176.             }
  177.             BCLDebug.Assert(kind == DateTimeKind.Local, "Internal Constructor is for local times only");
  178.             dateData = ((UInt64)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal));
  179.         }
  180.        
  181.         // Constructs a DateTime from a given year, month, and day. The
  182.         // time-of-day of the resulting DateTime is always midnight.
  183.         //
  184.         public DateTime(int year, int month, int day)
  185.         {
  186.             this.dateData = (UInt64)DateToTicks(year, month, day);
  187.         }
  188.        
  189.         // Constructs a DateTime from a given year, month, and day for
  190.         // the specified calendar. The
  191.         // time-of-day of the resulting DateTime is always midnight.
  192.         //
  193.         public DateTime(int year, int month, int day, Calendar calendar) : this(year, month, day, 0, 0, 0, calendar)
  194.         {
  195.         }
  196.        
  197.         // Constructs a DateTime from a given year, month, day, hour,
  198.         // minute, and second.
  199.         //
  200.         public DateTime(int year, int month, int day, int hour, int minute, int second)
  201.         {
  202.             this.dateData = (UInt64)(DateToTicks(year, month, day) + TimeToTicks(hour, minute, second));
  203.         }
  204.        
  205.         public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)
  206.         {
  207.             Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
  208.             if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
  209.                 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), "kind");
  210.             }
  211.             this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
  212.         }
  213.        
  214.         // Constructs a DateTime from a given year, month, day, hour,
  215.         // minute, and second for the specified calendar.
  216.         //
  217.         public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar)
  218.         {
  219.             if (calendar == null)
  220.                 throw new ArgumentNullException("calendar");
  221.             this.dateData = (UInt64)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
  222.         }
  223.        
  224.         // Constructs a DateTime from a given year, month, day, hour,
  225.         // minute, and second.
  226.         //
  227.         public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
  228.         {
  229.             Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
  230.             if (millisecond < 0 || millisecond >= MillisPerSecond) {
  231.                 throw new ArgumentOutOfRangeException("millisecond", String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1));
  232.             }
  233.             ticks += millisecond * TicksPerMillisecond;
  234.             if (ticks < MinTicks || ticks > MaxTicks)
  235.                 throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
  236.             this.dateData = (UInt64)ticks;
  237.         }
  238.        
  239.         public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
  240.         {
  241.             Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
  242.             if (millisecond < 0 || millisecond >= MillisPerSecond) {
  243.                 throw new ArgumentOutOfRangeException("millisecond", String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1));
  244.             }
  245.             ticks += millisecond * TicksPerMillisecond;
  246.             if (ticks < MinTicks || ticks > MaxTicks)
  247.                 throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
  248.             if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
  249.                 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), "kind");
  250.             }
  251.             this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
  252.         }
  253.        
  254.         // Constructs a DateTime from a given year, month, day, hour,
  255.         // minute, and second for the specified calendar.
  256.         //
  257.         public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar)
  258.         {
  259.             if (calendar == null)
  260.                 throw new ArgumentNullException("calendar");
  261.             Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
  262.             if (millisecond < 0 || millisecond >= MillisPerSecond) {
  263.                 throw new ArgumentOutOfRangeException("millisecond", String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1));
  264.             }
  265.             ticks += millisecond * TicksPerMillisecond;
  266.             if (ticks < MinTicks || ticks > MaxTicks)
  267.                 throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
  268.             this.dateData = (UInt64)ticks;
  269.         }
  270.        
  271.         public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind)
  272.         {
  273.             if (calendar == null)
  274.                 throw new ArgumentNullException("calendar");
  275.             Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
  276.             if (millisecond < 0 || millisecond >= MillisPerSecond) {
  277.                 throw new ArgumentOutOfRangeException("millisecond", String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1));
  278.             }
  279.             ticks += millisecond * TicksPerMillisecond;
  280.             if (ticks < MinTicks || ticks > MaxTicks)
  281.                 throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
  282.             if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
  283.                 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), "kind");
  284.             }
  285.             this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
  286.         }
  287.        
  288.         private DateTime(SerializationInfo info, StreamingContext context)
  289.         {
  290.             if (info == null)
  291.                 throw new ArgumentNullException("info");
  292.            
  293.             bool foundTicks = false;
  294.             bool foundDateData = false;
  295.             Int64 serializedTicks = 0;
  296.             UInt64 serializedDateData = 0;
  297.            
  298.            
  299.             // Get the data
  300.             SerializationInfoEnumerator enumerator = info.GetEnumerator();
  301.             while (enumerator.MoveNext()) {
  302.                 switch (enumerator.Name) {
  303.                     case TicksField:
  304.                         serializedTicks = Convert.ToInt64(enumerator.Value, CultureInfo.InvariantCulture);
  305.                         foundTicks = true;
  306.                         break;
  307.                     case DateDataField:
  308.                         serializedDateData = Convert.ToUInt64(enumerator.Value, CultureInfo.InvariantCulture);
  309.                         foundDateData = true;
  310.                         break;
  311.                     default:
  312.                         // Ignore other fields for forward compatability.
  313.                         break;
  314.                 }
  315.             }
  316.             if (foundDateData) {
  317.                 this.dateData = serializedDateData;
  318.             }
  319.             else if (foundTicks) {
  320.                 this.dateData = (UInt64)serializedTicks;
  321.             }
  322.             else {
  323.                 throw new SerializationException(Environment.GetResourceString("Serialization_MissingDateTimeData"));
  324.             }
  325.             Int64 ticks = InternalTicks;
  326.             if (ticks < MinTicks || ticks > MaxTicks) {
  327.                 throw new SerializationException(Environment.GetResourceString("Serialization_DateTimeTicksOutOfRange"));
  328.             }
  329.         }
  330.        
  331.        
  332.         private Int64 InternalTicks {
  333.             get { return (Int64)(dateData & TicksMask); }
  334.         }
  335.        
  336.         private UInt64 InternalKind {
  337.             get { return (dateData & FlagsMask); }
  338.         }
  339.        
  340.         // Returns the DateTime resulting from adding the given
  341.         // TimeSpan to this DateTime.
  342.         //
  343.         public DateTime Add(TimeSpan value)
  344.         {
  345.             return AddTicks(value._ticks);
  346.         }
  347.        
  348.         // Returns the DateTime resulting from adding a fractional number of
  349.         // time units to this DateTime.
  350.         private DateTime Add(double value, int scale)
  351.         {
  352.             long millis = (long)(value * scale + (value >= 0 ? 0.5 : -0.5));
  353.             if (millis <= -MaxMillis || millis >= MaxMillis)
  354.                 throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
  355.             return AddTicks(millis * TicksPerMillisecond);
  356.         }
  357.        
  358.         // Returns the DateTime resulting from adding a fractional number of
  359.         // days to this DateTime. The result is computed by rounding the
  360.         // fractional number of days given by value to the nearest
  361.         // millisecond, and adding that interval to this DateTime. The
  362.         // value argument is permitted to be negative.
  363.         //
  364.         public DateTime AddDays(double value)
  365.         {
  366.             return Add(value, MillisPerDay);
  367.         }
  368.        
  369.         // Returns the DateTime resulting from adding a fractional number of
  370.         // hours to this DateTime. The result is computed by rounding the
  371.         // fractional number of hours given by value to the nearest
  372.         // millisecond, and adding that interval to this DateTime. The
  373.         // value argument is permitted to be negative.
  374.         //
  375.         public DateTime AddHours(double value)
  376.         {
  377.             return Add(value, MillisPerHour);
  378.         }
  379.        
  380.         // Returns the DateTime resulting from the given number of
  381.         // milliseconds to this DateTime. The result is computed by rounding
  382.         // the number of milliseconds given by value to the nearest integer,
  383.         // and adding that interval to this DateTime. The value
  384.         // argument is permitted to be negative.
  385.         //
  386.         public DateTime AddMilliseconds(double value)
  387.         {
  388.             return Add(value, 1);
  389.         }
  390.        
  391.         // Returns the DateTime resulting from adding a fractional number of
  392.         // minutes to this DateTime. The result is computed by rounding the
  393.         // fractional number of minutes given by value to the nearest
  394.         // millisecond, and adding that interval to this DateTime. The
  395.         // value argument is permitted to be negative.
  396.         //
  397.         public DateTime AddMinutes(double value)
  398.         {
  399.             return Add(value, MillisPerMinute);
  400.         }
  401.        
  402.         // Returns the DateTime resulting from adding the given number of
  403.         // months to this DateTime. The result is computed by incrementing
  404.         // (or decrementing) the year and month parts of this DateTime by
  405.         // months months, and, if required, adjusting the day part of the
  406.         // resulting date downwards to the last day of the resulting month in the
  407.         // resulting year. The time-of-day part of the result is the same as the
  408.         // time-of-day part of this DateTime.
  409.         //
  410.         // In more precise terms, considering this DateTime to be of the
  411.         // form y / m / d + t, where y is the
  412.         // year, m is the month, d is the day, and t is the
  413.         // time-of-day, the result is y1 / m1 / d1 + t,
  414.         // where y1 and m1 are computed by adding months months
  415.         // to y and m, and d1 is the largest value less than
  416.         // or equal to d that denotes a valid day in month m1 of year
  417.         // y1.
  418.         //
  419.         public DateTime AddMonths(int months)
  420.         {
  421.             if (months < -120000 || months > 120000)
  422.                 throw new ArgumentOutOfRangeException("months", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadMonths"));
  423.             int y = GetDatePart(DatePartYear);
  424.             int m = GetDatePart(DatePartMonth);
  425.             int d = GetDatePart(DatePartDay);
  426.             int i = m - 1 + months;
  427.             if (i >= 0) {
  428.                 m = i % 12 + 1;
  429.                 y = y + i / 12;
  430.             }
  431.             else {
  432.                 m = 12 + (i + 1) % 12;
  433.                 y = y + (i - 11) / 12;
  434.             }
  435.             if (y < 1 || y > 9999) {
  436.                 throw new ArgumentOutOfRangeException("months", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
  437.             }
  438.             int days = DaysInMonth(y, m);
  439.             if (d > days)
  440.                 d = days;
  441.             return new DateTime((UInt64)(DateToTicks(y, m, d) + InternalTicks % TicksPerDay) | InternalKind);
  442.         }
  443.        
  444.         // Returns the DateTime resulting from adding a fractional number of
  445.         // seconds to this DateTime. The result is computed by rounding the
  446.         // fractional number of seconds given by value to the nearest
  447.         // millisecond, and adding that interval to this DateTime. The
  448.         // value argument is permitted to be negative.
  449.         //
  450.         public DateTime AddSeconds(double value)
  451.         {
  452.             return Add(value, MillisPerSecond);
  453.         }
  454.        
  455.         // Returns the DateTime resulting from adding the given number of
  456.         // 100-nanosecond ticks to this DateTime. The value argument
  457.         // is permitted to be negative.
  458.         //
  459.         public DateTime AddTicks(long value)
  460.         {
  461.             long ticks = InternalTicks;
  462.             if (value > MaxTicks - ticks || value < MinTicks - ticks) {
  463.                 throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
  464.             }
  465.             return new DateTime((UInt64)(ticks + value) | InternalKind);
  466.         }
  467.        
  468.         // Returns the DateTime resulting from adding the given number of
  469.         // years to this DateTime. The result is computed by incrementing
  470.         // (or decrementing) the year part of this DateTime by value
  471.         // years. If the month and day of this DateTime is 2/29, and if the
  472.         // resulting year is not a leap year, the month and day of the resulting
  473.         // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
  474.         // parts of the result are the same as those of this DateTime.
  475.         //
  476.         public DateTime AddYears(int value)
  477.         {
  478.             if (value < -10000 || value > 10000)
  479.                 throw new ArgumentOutOfRangeException("years", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadYears"));
  480.             return AddMonths(value * 12);
  481.         }
  482.        
  483.         // Compares two DateTime values, returning an integer that indicates
  484.         // their relationship.
  485.         //
  486.         public static int Compare(DateTime t1, DateTime t2)
  487.         {
  488.             Int64 ticks1 = t1.InternalTicks;
  489.             Int64 ticks2 = t2.InternalTicks;
  490.             if (ticks1 > ticks2)
  491.                 return 1;
  492.             if (ticks1 < ticks2)
  493.                 return -1;
  494.             return 0;
  495.         }
  496.        
  497.         // Compares this DateTime to a given object. This method provides an
  498.         // implementation of the IComparable interface. The object
  499.         // argument must be another DateTime, or otherwise an exception
  500.         // occurs. Null is considered less than any instance.
  501.         //
  502.         // Returns a value less than zero if this object
  503.         public int CompareTo(object value)
  504.         {
  505.             if (value == null)
  506.                 return 1;
  507.             if (!(value is DateTime)) {
  508.                 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTime"));
  509.             }
  510.            
  511.             long valueTicks = ((DateTime)value).InternalTicks;
  512.             long ticks = InternalTicks;
  513.             if (ticks > valueTicks)
  514.                 return 1;
  515.             if (ticks < valueTicks)
  516.                 return -1;
  517.             return 0;
  518.         }
  519.        
  520.         public int CompareTo(DateTime value)
  521.         {
  522.             long valueTicks = value.InternalTicks;
  523.             long ticks = InternalTicks;
  524.             if (ticks > valueTicks)
  525.                 return 1;
  526.             if (ticks < valueTicks)
  527.                 return -1;
  528.             return 0;
  529.         }
  530.        
  531.         // Returns the tick count corresponding to the given year, month, and day.
  532.         // Will check the if the parameters are valid.
  533.         private static long DateToTicks(int year, int month, int day)
  534.         {
  535.             if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) {
  536.                 int[] days = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
  537.                 if (day >= 1 && day <= days[month] - days[month - 1]) {
  538.                     int y = year - 1;
  539.                     int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
  540.                     return n * TicksPerDay;
  541.                 }
  542.             }
  543.             throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
  544.         }
  545.        
  546.         // Return the tick count corresponding to the given hour, minute, second.
  547.         // Will check the if the parameters are valid.
  548.         private static long TimeToTicks(int hour, int minute, int second)
  549.         {
  550.             //TimeSpan.TimeToTicks is a family access function which does no error checking, so
  551.             //we need to put some error checking out here.
  552.             if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) {
  553.                 return (TimeSpan.TimeToTicks(hour, minute, second));
  554.             }
  555.             throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
  556.         }
  557.        
  558.         // Returns the number of days in the month given by the year and
  559.         // month arguments.
  560.         //
  561.         public static int DaysInMonth(int year, int month)
  562.         {
  563.             if (month < 1 || month > 12)
  564.                 throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
  565.             // IsLeapYear checks the year argument
  566.             int[] days = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
  567.             return days[month] - days[month - 1];
  568.         }
  569.        
  570.         // Converts an OLE Date to a tick count.
  571.         // This function is duplicated in COMDateTime.cpp
  572.         static internal long DoubleDateToTicks(double value)
  573.         {
  574.             if (value >= OADateMaxAsDouble || value <= OADateMinAsDouble)
  575.                 throw new ArgumentException(Environment.GetResourceString("Arg_OleAutDateInvalid"));
  576.             long millis = (long)(value * MillisPerDay + (value >= 0 ? 0.5 : -0.5));
  577.             // The interesting thing here is when you have a value like 12.5 it all positive 12 days and 12 hours from 01/01/1899
  578.             // However if you a value of -12.25 it is minus 12 days but still positive 6 hours, almost as though you meant -11.75 all negative
  579.             // This line below fixes up the millis in the negative case
  580.             if (millis < 0) {
  581.                 millis -= (millis % MillisPerDay) * 2;
  582.             }
  583.            
  584.             millis += DoubleDateOffset / TicksPerMillisecond;
  585.            
  586.             if (millis < 0 || millis >= MaxMillis)
  587.                 throw new ArgumentException(Environment.GetResourceString("Arg_OleAutDateScale"));
  588.             return millis * TicksPerMillisecond;
  589.         }
  590.        
  591.         // Checks if this DateTime is equal to a given object. Returns
  592.         // true if the given object is a boxed DateTime and its value
  593.         // is equal to the value of this DateTime. Returns false
  594.         // otherwise.
  595.         //
  596.         public override bool Equals(object value)
  597.         {
  598.             if (value is DateTime) {
  599.                 return InternalTicks == ((DateTime)value).InternalTicks;
  600.             }
  601.             return false;
  602.         }
  603.        
  604.         public bool Equals(DateTime value)
  605.         {
  606.             return InternalTicks == value.InternalTicks;
  607.         }
  608.        
  609.         // Compares two DateTime values for equality. Returns true if
  610.         // the two DateTime values are equal, or false if they are
  611.         // not equal.
  612.         //
  613.         public static bool Equals(DateTime t1, DateTime t2)
  614.         {
  615.             return t1.InternalTicks == t2.InternalTicks;
  616.         }
  617.        
  618.         public static DateTime FromBinary(Int64 dateData)
  619.         {
  620.             if ((dateData & (unchecked((Int64)LocalMask))) != 0) {
  621.                 // Local times need to be adjusted as you move from one time zone to another,
  622.                 // just as they are when serializing in text. As such the format for local times
  623.                 // changes to store the ticks of the UTC time, but with flags that look like a
  624.                 // local date.
  625.                 Int64 ticks = dateData & (unchecked((Int64)TicksMask));
  626.                 // Negative ticks are stored in the top part of the range and should be converted back into a negative number
  627.                 if (ticks > TicksCeiling - TicksPerDay) {
  628.                     ticks = ticks - TicksCeiling;
  629.                 }
  630.                 // Convert the ticks back to local. If the UTC ticks are out of range, we need to default to
  631.                 // the UTC offset from MinValue and MaxValue to be consistent with Parse.
  632.                 bool isAmbiguousLocalDst = false;
  633.                 Int64 offsetTicks;
  634.                 if (ticks < MinTicks) {
  635.                     offsetTicks = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.MinValue).Ticks;
  636.                 }
  637.                 else if (ticks > MaxTicks) {
  638.                     offsetTicks = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.MaxValue).Ticks;
  639.                 }
  640.                 else {
  641.                     // Because the ticks conversion between UTC and local is lossy, we need to capture whether the
  642.                     // time is in a repeated hour so that it can be passed to the DateTime constructor.
  643.                     CurrentSystemTimeZone tz = (CurrentSystemTimeZone)TimeZone.CurrentTimeZone;
  644.                     offsetTicks = tz.GetUtcOffsetFromUniversalTime(new DateTime(ticks), ref isAmbiguousLocalDst);
  645.                 }
  646.                 ticks += offsetTicks;
  647.                 // Another behaviour of parsing is to cause small times to wrap around, so that they can be used
  648.                 // to compare times of day
  649.                 if (ticks < 0) {
  650.                     ticks += TicksPerDay;
  651.                 }
  652.                 if (ticks < MinTicks || ticks > MaxTicks) {
  653.                     throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), "dateData");
  654.                 }
  655.                 return new DateTime(ticks, DateTimeKind.Local, isAmbiguousLocalDst);
  656.             }
  657.             else {
  658.                 return DateTime.FromBinaryRaw(dateData);
  659.             }
  660.         }
  661.        
  662.         // A version of ToBinary that uses the real representation and does not adjust local times. This is needed for
  663.         // scenarios where the serialized data must maintain compatability
  664.         static internal DateTime FromBinaryRaw(Int64 dateData)
  665.         {
  666.             Int64 ticks = dateData & (Int64)TicksMask;
  667.             if (ticks < MinTicks || ticks > MaxTicks)
  668.                 throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), "dateData");
  669.             return new DateTime((UInt64)dateData);
  670.         }
  671.        
  672.         // Creates a DateTime from a Windows filetime. A Windows filetime is
  673.         // a long representing the date and time as the number of
  674.         // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
  675.         //
  676.         public static DateTime FromFileTime(long fileTime)
  677.         {
  678.             return FromFileTimeUtc(fileTime).ToLocalTime();
  679.         }
  680.        
  681.         public static DateTime FromFileTimeUtc(long fileTime)
  682.         {
  683.             if (fileTime < 0 || fileTime > MaxTicks - FileTimeOffset) {
  684.                 throw new ArgumentOutOfRangeException("fileTime", Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
  685.             }
  686.            
  687.             // This is the ticks in Universal time for this fileTime.
  688.             long universalTicks = fileTime + FileTimeOffset;
  689.             return new DateTime(universalTicks, DateTimeKind.Utc);
  690.         }
  691.        
  692.         // Creates a DateTime from an OLE Automation Date.
  693.         //
  694.         public static DateTime FromOADate(double d)
  695.         {
  696.             return new DateTime(DoubleDateToTicks(d), DateTimeKind.Unspecified);
  697.         }
  698.        
  699.         [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
  700.         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  701.         {
  702.             if (info == null) {
  703.                 throw new ArgumentNullException("info");
  704.             }
  705.            
  706.             // Serialize both the old and the new format
  707.             info.AddValue(TicksField, InternalTicks);
  708.             info.AddValue(DateDataField, dateData);
  709.         }
  710.        
  711.         public bool IsDaylightSavingTime()
  712.         {
  713.             return TimeZone.CurrentTimeZone.IsDaylightSavingTime(this);
  714.         }
  715.        
  716.         public static DateTime SpecifyKind(DateTime value, DateTimeKind kind)
  717.         {
  718.             return new DateTime(value.InternalTicks, kind);
  719.         }
  720.        
  721.         public Int64 ToBinary()
  722.         {
  723.             if (Kind == DateTimeKind.Local) {
  724.                 // Local times need to be adjusted as you move from one time zone to another,
  725.                 // just as they are when serializing in text. As such the format for local times
  726.                 // changes to store the ticks of the UTC time, but with flags that look like a
  727.                 // local date.
  728.                
  729.                 // To match serialization in text we need to be able to handle cases where
  730.                 // the UTC value would be out of range. Unused parts of the ticks range are
  731.                 // used for this, so that values just past max value are stored just past the
  732.                 // end of the maximum range, and values just below minimum value are stored
  733.                 // at the end of the ticks area, just below 2^62.
  734.                 TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(this);
  735.                 Int64 ticks = Ticks;
  736.                 Int64 storedTicks = ticks - offset.Ticks;
  737.                 if (storedTicks < 0) {
  738.                     storedTicks = TicksCeiling + storedTicks;
  739.                 }
  740.                 return storedTicks | (unchecked((Int64)LocalMask));
  741.             }
  742.             else {
  743.                 return (Int64)dateData;
  744.             }
  745.         }
  746.        
  747.         // Return the underlying data, without adjust local times to the right time zone. Needed if performance
  748.         // or compatability are important.
  749.         internal Int64 ToBinaryRaw()
  750.         {
  751.             return (Int64)dateData;
  752.         }
  753.        
  754.         // Returns the date part of this DateTime. The resulting value
  755.         // corresponds to this DateTime with the time-of-day part set to
  756.         // zero (midnight).
  757.         //
  758.         public DateTime Date {
  759.             get {
  760.                 Int64 ticks = InternalTicks;
  761.                 return new DateTime((UInt64)(ticks - ticks % TicksPerDay) | InternalKind);
  762.             }
  763.         }
  764.        
  765.         // Returns a given date part of this DateTime. This method is used
  766.         // to compute the year, day-of-year, month, or day part.
  767.         private int GetDatePart(int part)
  768.         {
  769.             Int64 ticks = InternalTicks;
  770.             // n = number of days since 1/1/0001
  771.             int n = (int)(ticks / TicksPerDay);
  772.             // y400 = number of whole 400-year periods since 1/1/0001
  773.             int y400 = n / DaysPer400Years;
  774.             // n = day number within 400-year period
  775.             n -= y400 * DaysPer400Years;
  776.             // y100 = number of whole 100-year periods within 400-year period
  777.             int y100 = n / DaysPer100Years;
  778.             // Last 100-year period has an extra day, so decrement result if 4
  779.             if (y100 == 4)
  780.                 y100 = 3;
  781.             // n = day number within 100-year period
  782.             n -= y100 * DaysPer100Years;
  783.             // y4 = number of whole 4-year periods within 100-year period
  784.             int y4 = n / DaysPer4Years;
  785.             // n = day number within 4-year period
  786.             n -= y4 * DaysPer4Years;
  787.             // y1 = number of whole years within 4-year period
  788.             int y1 = n / DaysPerYear;
  789.             // Last year has an extra day, so decrement result if 4
  790.             if (y1 == 4)
  791.                 y1 = 3;
  792.             // If year was requested, compute and return it
  793.             if (part == DatePartYear) {
  794.                 return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;
  795.             }
  796.             // n = day number within year
  797.             n -= y1 * DaysPerYear;
  798.             // If day-of-year was requested, return it
  799.             if (part == DatePartDayOfYear)
  800.                 return n + 1;
  801.             // Leap year calculation looks different from IsLeapYear since y1, y4,
  802.             // and y100 are relative to year 1, not year 0
  803.             bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3);
  804.             int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
  805.             // All months have less than 32 days, so n >> 5 is a good conservative
  806.             // estimate for the month
  807.             int m = n >> 5 + 1;
  808.             // m = 1-based month number
  809.             while (n >= days[m])
  810.                 m++;
  811.             // If month was requested, return it
  812.             if (part == DatePartMonth)
  813.                 return m;
  814.             // Return 1-based day-of-month
  815.             return n - days[m - 1] + 1;
  816.         }
  817.        
  818.         // Returns the day-of-month part of this DateTime. The returned
  819.         // value is an integer between 1 and 31.
  820.         //
  821.         public int Day {
  822.             get { return GetDatePart(DatePartDay); }
  823.         }
  824.        
  825.         // Returns the day-of-week part of this DateTime. The returned value
  826.         // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
  827.         // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
  828.         // Thursday, 5 indicates Friday, and 6 indicates Saturday.
  829.         //
  830.         public DayOfWeek DayOfWeek {
  831.             get { return (DayOfWeek)((InternalTicks / TicksPerDay + 1) % 7); }
  832.         }
  833.        
  834.         // Returns the day-of-year part of this DateTime. The returned value
  835.         // is an integer between 1 and 366.
  836.         //
  837.         public int DayOfYear {
  838.             get { return GetDatePart(DatePartDayOfYear); }
  839.         }
  840.        
  841.         // Returns the hash code for this DateTime.
  842.         //
  843.         public override int GetHashCode()
  844.         {
  845.             Int64 ticks = InternalTicks;
  846.             return unchecked((int)ticks) ^ (int)(ticks >> 32);
  847.         }
  848.        
  849.         // Returns the hour part of this DateTime. The returned value is an
  850.         // integer between 0 and 23.
  851.         //
  852.         public int Hour {
  853.             get { return (int)((InternalTicks / TicksPerHour) % 24); }
  854.         }
  855.        
  856.         internal bool IsAmbiguousDaylightSavingTime()
  857.         {
  858.             return (InternalKind == KindLocalAmbiguousDst);
  859.         }
  860.        
  861.         public DateTimeKind Kind {
  862.             get {
  863.                 switch (InternalKind) {
  864.                     case KindUnspecified:
  865.                         return DateTimeKind.Unspecified;
  866.                     case KindUtc:
  867.                         return DateTimeKind.Utc;
  868.                     default:
  869.                         return DateTimeKind.Local;
  870.                 }
  871.             }
  872.         }
  873.        
  874.         // Returns the millisecond part of this DateTime. The returned value
  875.         // is an integer between 0 and 999.
  876.         //
  877.         public int Millisecond {
  878.             get { return (int)((InternalTicks / TicksPerMillisecond) % 1000); }
  879.         }
  880.        
  881.         // Returns the minute part of this DateTime. The returned value is
  882.         // an integer between 0 and 59.
  883.         //
  884.         public int Minute {
  885.             get { return (int)((InternalTicks / TicksPerMinute) % 60); }
  886.         }
  887.        
  888.         // Returns the month part of this DateTime. The returned value is an
  889.         // integer between 1 and 12.
  890.         //
  891.         public int Month {
  892.             get { return GetDatePart(DatePartMonth); }
  893.         }
  894.        
  895.         // Returns a DateTime representing the current date and time. The
  896.         // resolution of the returned value depends on the system timer. For
  897.         // Windows NT 3.5 and later the timer resolution is approximately 10ms,
  898.         // for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98
  899.         // it is approximately 55ms.
  900.         //
  901.         public static DateTime Now {
  902.             get { return UtcNow.ToLocalTime(); }
  903.         }
  904.        
  905.         public static DateTime UtcNow {
  906.             get {
  907.                 // following code is tuned for speed. Don't change it without running benchmark.
  908.                 long ticks = 0;
  909.                 ticks = GetSystemTimeAsFileTime();
  910.                 return new DateTime(((UInt64)(ticks + FileTimeOffset)) | KindUtc);
  911.             }
  912.         }
  913.        
  914.        
  915.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  916.         static internal extern long GetSystemTimeAsFileTime();
  917.        
  918.        
  919.        
  920.         // Returns the second part of this DateTime. The returned value is
  921.         // an integer between 0 and 59.
  922.         //
  923.         public int Second {
  924.             get { return (int)((InternalTicks / TicksPerSecond) % 60); }
  925.         }
  926.        
  927.         // Returns the tick count for this DateTime. The returned value is
  928.         // the number of 100-nanosecond intervals that have elapsed since 1/1/0001
  929.         // 12:00am.
  930.         //
  931.         public long Ticks {
  932.             get { return InternalTicks; }
  933.         }
  934.        
  935.         // Returns the time-of-day part of this DateTime. The returned value
  936.         // is a TimeSpan that indicates the time elapsed since midnight.
  937.         //
  938.         public TimeSpan TimeOfDay {
  939.             get { return new TimeSpan(InternalTicks % TicksPerDay); }
  940.         }
  941.        
  942.         // Returns a DateTime representing the current date. The date part
  943.         // of the returned value is the current date, and the time-of-day part of
  944.         // the returned value is zero (midnight).
  945.         //
  946.         public static DateTime Today {
  947.             get { return DateTime.Now.Date; }
  948.         }
  949.        
  950.         // Returns the year part of this DateTime. The returned value is an
  951.         // integer between 1 and 9999.
  952.         //
  953.         public int Year {
  954.             get { return GetDatePart(DatePartYear); }
  955.         }
  956.        
  957.         // Checks whether a given year is a leap year. This method returns true if
  958.         // year is a leap year, or false if not.
  959.         //
  960.         public static bool IsLeapYear(int year)
  961.         {
  962.             if (year < 1 || year > 9999) {
  963.                 throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Year"));
  964.             }
  965.             return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
  966.         }
  967.        
  968.         // Constructs a DateTime from a string. The string must specify a
  969.         // date and optionally a time in a culture-specific or universal format.
  970.         // Leading and trailing whitespace characters are allowed.
  971.         //
  972.         public static DateTime Parse(string s)
  973.         {
  974.             return (DateTimeParse.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None));
  975.         }
  976.        
  977.         // Constructs a DateTime from a string. The string must specify a
  978.         // date and optionally a time in a culture-specific or universal format.
  979.         // Leading and trailing whitespace characters are allowed.
  980.         //
  981.         public static DateTime Parse(string s, IFormatProvider provider)
  982.         {
  983.             return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None));
  984.         }
  985.        
  986.         public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles)
  987.         {
  988.             DateTimeFormatInfo.ValidateStyles(styles, "styles");
  989.             return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), styles));
  990.         }
  991.        
  992.         // Constructs a DateTime from a string. The string must specify a
  993.         // date and optionally a time in a culture-specific or universal format.
  994.         // Leading and trailing whitespace characters are allowed.
  995.         //
  996.         public static DateTime ParseExact(string s, string format, IFormatProvider provider)
  997.         {
  998.             return (DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None));
  999.         }
  1000.        
  1001.         // Constructs a DateTime from a string. The string must specify a
  1002.         // date and optionally a time in a culture-specific or universal format.
  1003.         // Leading and trailing whitespace characters are allowed.
  1004.         //
  1005.         public static DateTime ParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style)
  1006.         {
  1007.             DateTimeFormatInfo.ValidateStyles(style, "style");
  1008.             return (DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style));
  1009.         }
  1010.        
  1011.         public static DateTime ParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style)
  1012.         {
  1013.             DateTimeFormatInfo.ValidateStyles(style, "style");
  1014.             return DateTimeParse.ParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style);
  1015.         }
  1016.        
  1017.         public TimeSpan Subtract(DateTime value)
  1018.         {
  1019.             return new TimeSpan(InternalTicks - value.InternalTicks);
  1020.         }
  1021.        
  1022.         public DateTime Subtract(TimeSpan value)
  1023.         {
  1024.             long ticks = InternalTicks;
  1025.             long valueTicks = value._ticks;
  1026.             if (ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) {
  1027.                 throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
  1028.             }
  1029.             return new DateTime((UInt64)(ticks - valueTicks) | InternalKind);
  1030.         }
  1031.        
  1032.         // This function is duplicated in COMDateTime.cpp
  1033.         private static double TicksToOADate(long value)
  1034.         {
  1035.             if (value == 0)
  1036.                 return 0.0;
  1037.             // Returns OleAut's zero'ed date value.
  1038.             if (value < TicksPerDay)
  1039.                 // This is a fix for VB. They want the default day to be 1/1/0001 rathar then 12/30/1899.
  1040.                 value += DoubleDateOffset;
  1041.             // We could have moved this fix down but we would like to keep the bounds check.
  1042.             if (value < OADateMinAsTicks)
  1043.                 throw new OverflowException(Environment.GetResourceString("Arg_OleAutDateInvalid"));
  1044.             // Currently, our max date == OA's max date (12/31/9999), so we don't
  1045.             // need an overflow check in that direction.
  1046.             long millis = (value - DoubleDateOffset) / TicksPerMillisecond;
  1047.             if (millis < 0) {
  1048.                 long frac = millis % MillisPerDay;
  1049.                 if (frac != 0)
  1050.                     millis -= (MillisPerDay + frac) * 2;
  1051.             }
  1052.             return (double)millis / MillisPerDay;
  1053.         }
  1054.        
  1055.         // Converts the DateTime instance into an OLE Automation compatible
  1056.         // double date.
  1057.         public double ToOADate()
  1058.         {
  1059.             return TicksToOADate(InternalTicks);
  1060.         }
  1061.        
  1062.         public long ToFileTime()
  1063.         {
  1064.             // Treats the input as local if it is not specified
  1065.             return ToUniversalTime().ToFileTimeUtc();
  1066.         }
  1067.        
  1068.         public long ToFileTimeUtc()
  1069.         {
  1070.             // Treats the input as universal if it is not specified
  1071.             long ticks = ((InternalKind & LocalMask) != 0) ? ToUniversalTime().InternalTicks : this.InternalTicks;
  1072.             ticks -= FileTimeOffset;
  1073.             if (ticks < 0) {
  1074.                 throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
  1075.             }
  1076.             return ticks;
  1077.         }
  1078.        
  1079.         public DateTime ToLocalTime()
  1080.         {
  1081.             return TimeZone.CurrentTimeZone.ToLocalTime(this);
  1082.         }
  1083.        
  1084.         public string ToLongDateString()
  1085.         {
  1086.             return DateTimeFormat.Format(this, "D", DateTimeFormatInfo.CurrentInfo);
  1087.         }
  1088.        
  1089.         public string ToLongTimeString()
  1090.         {
  1091.             return DateTimeFormat.Format(this, "T", DateTimeFormatInfo.CurrentInfo);
  1092.         }
  1093.        
  1094.         public string ToShortDateString()
  1095.         {
  1096.             return DateTimeFormat.Format(this, "d", DateTimeFormatInfo.CurrentInfo);
  1097.         }
  1098.        
  1099.         public string ToShortTimeString()
  1100.         {
  1101.             return DateTimeFormat.Format(this, "t", DateTimeFormatInfo.CurrentInfo);
  1102.         }
  1103.        
  1104.         public override string ToString()
  1105.         {
  1106.             return DateTimeFormat.Format(this, null, DateTimeFormatInfo.CurrentInfo);
  1107.         }
  1108.        
  1109.         public string ToString(string format)
  1110.         {
  1111.             return DateTimeFormat.Format(this, format, DateTimeFormatInfo.CurrentInfo);
  1112.         }
  1113.        
  1114.         public string ToString(IFormatProvider provider)
  1115.         {
  1116.             return DateTimeFormat.Format(this, null, DateTimeFormatInfo.GetInstance(provider));
  1117.         }
  1118.        
  1119.         public string ToString(string format, IFormatProvider provider)
  1120.         {
  1121.             return DateTimeFormat.Format(this, format, DateTimeFormatInfo.GetInstance(provider));
  1122.         }
  1123.        
  1124.         public DateTime ToUniversalTime()
  1125.         {
  1126.             return TimeZone.CurrentTimeZone.ToUniversalTime(this);
  1127.         }
  1128.        
  1129.         public static bool TryParse(string s, out DateTime result)
  1130.         {
  1131.             return DateTimeParse.TryParse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result);
  1132.         }
  1133.        
  1134.         public static bool TryParse(string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result)
  1135.         {
  1136.             DateTimeFormatInfo.ValidateStyles(styles, "styles");
  1137.             return DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), styles, out result);
  1138.         }
  1139.        
  1140.         public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result)
  1141.         {
  1142.             DateTimeFormatInfo.ValidateStyles(style, "style");
  1143.             return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result);
  1144.         }
  1145.        
  1146.         public static bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result)
  1147.         {
  1148.             DateTimeFormatInfo.ValidateStyles(style, "style");
  1149.             return DateTimeParse.TryParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style, out result);
  1150.         }
  1151.        
  1152.         public static DateTime operator +(DateTime d, TimeSpan t)
  1153.         {
  1154.             long ticks = d.InternalTicks;
  1155.             long valueTicks = t._ticks;
  1156.             if (valueTicks > MaxTicks - ticks || valueTicks < MinTicks - ticks) {
  1157.                 throw new ArgumentOutOfRangeException("t", Environment.GetResourceString("Overflow_DateArithmetic"));
  1158.             }
  1159.             return new DateTime((UInt64)(ticks + valueTicks) | d.InternalKind);
  1160.         }
  1161.        
  1162.         public static DateTime operator -(DateTime d, TimeSpan t)
  1163.         {
  1164.             long ticks = d.InternalTicks;
  1165.             long valueTicks = t._ticks;
  1166.             if (ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) {
  1167.                 throw new ArgumentOutOfRangeException("t", Environment.GetResourceString("Overflow_DateArithmetic"));
  1168.             }
  1169.             return new DateTime((UInt64)(ticks - valueTicks) | d.InternalKind);
  1170.         }
  1171.        
  1172.         public static TimeSpan operator -(DateTime d1, DateTime d2)
  1173.         {
  1174.             return new TimeSpan(d1.InternalTicks - d2.InternalTicks);
  1175.         }
  1176.        
  1177.         public static bool operator ==(DateTime d1, DateTime d2)
  1178.         {
  1179.             return d1.InternalTicks == d2.InternalTicks;
  1180.         }
  1181.        
  1182.         public static bool operator !=(DateTime d1, DateTime d2)
  1183.         {
  1184.             return d1.InternalTicks != d2.InternalTicks;
  1185.         }
  1186.        
  1187.         public static bool operator <(DateTime t1, DateTime t2)
  1188.         {
  1189.             return t1.InternalTicks < t2.InternalTicks;
  1190.         }
  1191.        
  1192.         public static bool operator <=(DateTime t1, DateTime t2)
  1193.         {
  1194.             return t1.InternalTicks <= t2.InternalTicks;
  1195.         }
  1196.        
  1197.         public static bool operator >(DateTime t1, DateTime t2)
  1198.         {
  1199.             return t1.InternalTicks > t2.InternalTicks;
  1200.         }
  1201.        
  1202.         public static bool operator >=(DateTime t1, DateTime t2)
  1203.         {
  1204.             return t1.InternalTicks >= t2.InternalTicks;
  1205.         }
  1206.        
  1207.        
  1208.         // Returns a string array containing all of the known date and time options for the
  1209.         // current culture. The strings returned are properly formatted date and
  1210.         // time strings for the current instance of DateTime.
  1211.         public string[] GetDateTimeFormats()
  1212.         {
  1213.             return (GetDateTimeFormats(CultureInfo.CurrentCulture));
  1214.         }
  1215.        
  1216.         // Returns a string array containing all of the known date and time options for the
  1217.         // using the information provided by IFormatProvider. The strings returned are properly formatted date and
  1218.         // time strings for the current instance of DateTime.
  1219.         public string[] GetDateTimeFormats(IFormatProvider provider)
  1220.         {
  1221.             return (DateTimeFormat.GetAllDateTimes(this, DateTimeFormatInfo.GetInstance(provider)));
  1222.         }
  1223.        
  1224.        
  1225.         // Returns a string array containing all of the date and time options for the
  1226.         // given format format and current culture. The strings returned are properly formatted date and
  1227.         // time strings for the current instance of DateTime.
  1228.         public string[] GetDateTimeFormats(char format)
  1229.         {
  1230.             return (GetDateTimeFormats(format, CultureInfo.CurrentCulture));
  1231.         }
  1232.        
  1233.         // Returns a string array containing all of the date and time options for the
  1234.         // given format format and given culture. The strings returned are properly formatted date and
  1235.         // time strings for the current instance of DateTime.
  1236.         public string[] GetDateTimeFormats(char format, IFormatProvider provider)
  1237.         {
  1238.             return (DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider)));
  1239.         }
  1240.        
  1241.         //
  1242.         // IValue implementation
  1243.         //
  1244.        
  1245.         public TypeCode GetTypeCode()
  1246.         {
  1247.             return TypeCode.DateTime;
  1248.         }
  1249.        
  1250.        
  1251.         /// <internalonly/>
  1252.         bool IConvertible.ToBoolean(IFormatProvider provider)
  1253.         {
  1254.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Boolean"));
  1255.         }
  1256.        
  1257.         /// <internalonly/>
  1258.         char IConvertible.ToChar(IFormatProvider provider)
  1259.         {
  1260.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Char"));
  1261.         }
  1262.        
  1263.         /// <internalonly/>
  1264.         sbyte IConvertible.ToSByte(IFormatProvider provider)
  1265.         {
  1266.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "SByte"));
  1267.         }
  1268.        
  1269.         /// <internalonly/>
  1270.         byte IConvertible.ToByte(IFormatProvider provider)
  1271.         {
  1272.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Byte"));
  1273.         }
  1274.        
  1275.         /// <internalonly/>
  1276.         short IConvertible.ToInt16(IFormatProvider provider)
  1277.         {
  1278.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Int16"));
  1279.         }
  1280.        
  1281.         /// <internalonly/>
  1282.         ushort IConvertible.ToUInt16(IFormatProvider provider)
  1283.         {
  1284.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "UInt16"));
  1285.         }
  1286.        
  1287.         /// <internalonly/>
  1288.         int IConvertible.ToInt32(IFormatProvider provider)
  1289.         {
  1290.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Int32"));
  1291.         }
  1292.        
  1293.         /// <internalonly/>
  1294.         uint IConvertible.ToUInt32(IFormatProvider provider)
  1295.         {
  1296.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "UInt32"));
  1297.         }
  1298.        
  1299.         /// <internalonly/>
  1300.         long IConvertible.ToInt64(IFormatProvider provider)
  1301.         {
  1302.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Int64"));
  1303.         }
  1304.        
  1305.         /// <internalonly/>
  1306.         ulong IConvertible.ToUInt64(IFormatProvider provider)
  1307.         {
  1308.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "UInt64"));
  1309.         }
  1310.        
  1311.         /// <internalonly/>
  1312.         float IConvertible.ToSingle(IFormatProvider provider)
  1313.         {
  1314.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Single"));
  1315.         }
  1316.        
  1317.         /// <internalonly/>
  1318.         double IConvertible.ToDouble(IFormatProvider provider)
  1319.         {
  1320.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Double"));
  1321.         }
  1322.        
  1323.         /// <internalonly/>
  1324.         decimal IConvertible.ToDecimal(IFormatProvider provider)
  1325.         {
  1326.             throw new InvalidCastException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), "DateTime", "Decimal"));
  1327.         }
  1328.        
  1329.         /// <internalonly/>
  1330.         DateTime IConvertible.ToDateTime(IFormatProvider provider)
  1331.         {
  1332.             return this;
  1333.         }
  1334.        
  1335.         /// <internalonly/>
  1336.         object IConvertible.ToType(Type type, IFormatProvider provider)
  1337.         {
  1338.             return Convert.DefaultToType((IConvertible)this, type, provider);
  1339.         }
  1340.        
  1341.         // Tries to construct a DateTime from a given year, month, day, hour,
  1342.         // minute, second and millisecond.
  1343.         //
  1344.         static internal bool TryCreate(int year, int month, int day, int hour, int minute, int second, int millisecond, out DateTime result)
  1345.         {
  1346.             result = DateTime.MinValue;
  1347.             if (year < 1 || year > 9999 || month < 1 || month > 12) {
  1348.                 return false;
  1349.             }
  1350.             int[] days = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
  1351.             if (day < 1 || day > days[month] - days[month - 1]) {
  1352.                 return false;
  1353.             }
  1354.             if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || second < 0 || second >= 60) {
  1355.                 return false;
  1356.             }
  1357.             if (millisecond < 0 || millisecond >= MillisPerSecond) {
  1358.                 return false;
  1359.             }
  1360.             long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
  1361.            
  1362.             ticks += millisecond * TicksPerMillisecond;
  1363.             if (ticks < MinTicks || ticks > MaxTicks) {
  1364.                 return false;
  1365.             }
  1366.             result = new DateTime(ticks, DateTimeKind.Unspecified);
  1367.             return true;
  1368.         }
  1369.     }
  1370. }

Developer Fusion