DateTime.cs 69 KB

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