Pages

Thursday, December 2, 2021

.NET 6: DateOnly and TimeOnly Types

In this post, let's have a look at two new types that got added to .NET Base Class Library (core set) in .NET 6 and that is DateOnly and TimeOnly. These were added to System namespace just like other DateTime types.

Let's consider the following DateTime.

DateTime datetime = new(2021, 12, 15);
Console.WriteLine(datetime);                 // 15/12/2021 12:00:00 am

Since it's a DateTime, it has the Date component and a Time component which makes perfect sense. Now let's say you want to extract the Date component and the Time component separately. That's where the new DateOnly and TimeOnly types comes into the picture.

DateOnly dateonly = DateOnly.FromDateTime(datetime);
Console.WriteLine(dateonly);                 // 15/12/2021
 
TimeOnly timeonly = TimeOnly.FromDateTime(datetime);
Console.WriteLine(timeonly);                 // 12:00 am

You can construct DateOnly and TimeOnly as you construct DateTime. And you have all the different constructor overloads to create DateOnly and TimeOnly the way you want. For example,

DateOnly dateonly = new(2021, 12, 15);
Console.WriteLine(dateonly);                 // 15/12/2021
 
TimeOnly timeonly = new(13, 30);
Console.WriteLine(timeonly);                 // 1:30 pm

DateOnly and TimeOnly types have their own Properties and Methods that you can use. For example,

// Some of DateOnly Properties
Console.WriteLine(dateonly.Day);             // 15
Console.WriteLine(dateonly.DayOfWeek);       // Wednesday Console.WriteLine(dateonly.Month);           // 12 Console.WriteLine(dateonly.Year);            // 2021 // Some of TimeOnly Properties Console.WriteLine(timeonly.Hour);            // 13 Console.WriteLine(timeonly.Minute);          // 30 Console.WriteLine(timeonly.Second);          // 0 // Some of DateOnly Methods Console.WriteLine(dateonly.AddDays(30));     // 14/01/2022 Console.WriteLine(dateonly.AddYears(1));     // 15/12/2022 // Some of TimeOnly Methods Console.WriteLine(timeonly.AddHours(4));     // 5:30 pm Console.WriteLine(timeonly.AddMinutes(270)); // 6:00 pm

These two new types are going to be super useful, specially DateOnly. There are a lot of scenarios we don't care about the Time component, so it's going to be very handy.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment