If there was a poll to find that one little feature every C# developer would love to have in .Net, then it is most likely the ability to store Date and Time individually. For years now, we had to use DateTime to represent Date when the Time part of the object had to be ignored. The same thing happened when we wanted to save time and had to ignore the Date of the DateTime component.
DateOnly
- var dateOnlyFirst = new DateOnly(2020, 2, 16);
- var dateOnlySecond = DateOnly.FromDateTime(DateTime.Now);
- Console.WriteLine(dateOnlyFirst);
- Console.WriteLine(dateOnlySecond);
- // Output
- 16-02-2020
- 04-06-2021
- private readonly int _dayNumber;
- // Maps to Jan 1st year 1
- private const int MinDayNumber = 0;
- // Maps to December 31 year 9999. The value calculated from "new DateTime(9999, 12, 31).Ticks / TimeSpan.TicksPerDay"
- private const int MaxDayNumber = 3_652_058;
- public DateOnly(int year, int month, int day) => _dayNumber = DayNumberFromDateTime(new DateTime(year, month, day));
- public static DateOnly FromDateTime(DateTime dateTime) => new DateOnly(DayNumberFromDateTime(dateTime));
- private static int DayNumberFromDateTime(DateTime dt) => (int)(dt.Ticks / TimeSpan.TicksPerDay);
TimeOnly
- var timeOnlyFirst = new TimeOnly(10,10,10);
- var timeOnlySecond = TimeOnly.FromDateTime(DateTime.Now);
- Console.WriteLine(timeOnlyFirst);
- Console.WriteLine(timeOnlySecond);
- //Output
- 10:10
- 05:35
- // represent the number of ticks map to the time of the day. 1 ticks = 100-nanosecond in time measurements.
- private readonly long _ticks;
- // MinTimeTicks is the ticks for the midnight time 00:00:00.000 AM
- private const long MinTimeTicks = 0;
- // MaxTimeTicks is the max tick value for the time in the day. It is calculated using DateTime.Today.AddTicks(-1).TimeOfDay.Ticks.
- private const long MaxTimeTicks = 863_999_999_999;
- public TimeOnly(int hour, int minute, int second) : this(DateTime.TimeToTicks(hour, minute, second, 0)) {}
- public TimeOnly(long ticks)
- {
- if ((ulong)ticks > MaxTimeTicks)
- {
- throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_TimeOnlyBadTicks);
- }
- _ticks = ticks;
- }

khushboo kumariPosted Jun 6, 2021, 3:16 PM
Learn programming on KK CodesWhatsApp : https://chat.whatsapp.com/BEuzFKt1xh25UvKeykrVSj Telegram : https://t.me/joinchat/m3j4r8I2c80wMWE1 Facebook : https://www.facebook.com/groups/243228876878806 Website : https://kkcodes.in/ YouTube : https://www.youtube.com/channel/UC2mNapkDneELS_N-m_zNvpQ Instagram : https://www.instagram.com/kkcodes.in/ LinkedIn : https://www.linkedin.com/groups/12523807/