Hi lovely readers,
We probably all know the pain of using DateTime while just needing a date without time or a time without a day. Well, .NET came with a solution that still isn’t that widely used. In this blog post, we’re going to focus on the type DateOnly
Does your application heavily rely on dates and not time? Do you want to learn how to make your dates even better, and easier to serialize? Continue reading and I’ll show you how.
Why DateOnly
DateOnly is great in situations where you’re heavily focused on dates. Here are some scenarios where DateOnly proves to be a great alternative to DateTime:
Simplicity and Readability:
When your application deals primarily with event dates and doesn't require time tracking, DateOnly provides a better option because the time doesn’t matter.
Database Operations:
Working with databases that store date information without time becomes seamless with DateOnly.
User Interfaces:
In input forms or date pickers, where time is not important, DateOnly simplifies the user experience by focusing on just the date.
Comparisons:
DateOnly is a great pick if your logic involves comparing days between dates. It has methods built in to compare dates.
Consistency in Codebase:
For codebases that heavily rely on dates, using DateOnly throughout helps with consistency.
Avoiding Time Zone Complexity:
Because DateOnly doesn’t focus on time, you don’t have time zone complexities at all. This makes working with DateOnly way easier.
How to use DateOnly
Now that we've explored why DateOnly is a great choice in multiple scenarios, let's dive into how to use DateOnly in your C# projects.
Initialize DateOnly
Creating a DateOnly instance is straightforward. You can set a specific date using the constructor in yyyy d m:
DateOnly specificDate = new DateOnly(2024, 2, 1); //year, month, day
If you want to initialize a DateOnly variable with today's date, you can use the ‘FromDateTime’ method:
DateOnly today = DateOnly.FromDateTime(DateTime.Now);
You can write it to the console like every other variable:
Console.WriteLine(specificDate); // 01/02/2024
Console.WriteLine(today); // [day]/[month]/[year] of today
This date format can depend on the location settings on your machine.
Formatting the DateOnly value
Do you want to make sure that the date format is consistent? Do you want to use another type of calendar (Hebrew or Japanese calendar for example)? Or do you want to print the day in full like Thursday, February 2? That’s all possible.
Changing the date format from [day]/[month]/[year] to [month]/[day]/[year]:
DateOnly specificDate = new DateOnly(2024, 12, 16);
var dateFormatted = specificDate.ToString("MM/dd/yyyy");
Console.WriteLine(dateFormatted); // 12/16/2024
Changing to the Japanese calendar:
using System.Globalization;
DateOnly specificDate = new DateOnly(2024, 12, 16, new JapaneseCalendar());
var dateFormatted = specificDate.ToString("MM/dd/yyyy");
Console.WriteLine(dateFormatted); //12/16/4042
Changing from short format to long format date (format depends on your PC location settings):
DateOnly specificDate = new DateOnly(2024, 12, 16);
var dateFormatted = specificDate.ToLongDateString();
Console.WriteLine(dateFormatted); //Monday, 16 December 2024
Logic with DateOnly
DateOnly supports date operations like adding or subtracting days, months, or years. Here's how you can do it.
Adding and Subtracting Days:
DateOnly today = DateOnly.FromDateTime(DateTime.Now);
DateOnly tomorrow = today.AddDays(1);
DateOnly yesterday = today.AddDays(-1);
Console.WriteLine(tomorrow); // Tomorrow's date
Console.WriteLine(yesterday); // Yesterday's date
Adding and Subtracting Months:
DateOnly thisMonth = DateOnly.FromDateTime(DateTime.Now);
DateOnly nextMonth = thisMonth.AddMonths(1);
DateOnly previousMonth = thisMonth.AddMonths(-1);
Console.WriteLine(nextMonth); // Next month's date
Console.WriteLine(previousMonth); // Previous month's date
Adding and Subtracting Years:
DateOnly thisYear = DateOnly.FromDateTime(DateTime.Now);
DateOnly nextYear = thisYear.AddYears(1);
DateOnly lastYear = thisYear.AddYears(-1);
Console.WriteLine(nextYear); // Next year's date
Console.WriteLine(lastYear); // Last year's date
Serialization
Serialization is often crucial when dealing with dates in applications. DateOnly simplifies this process. For instance, when working with JSON:
using System.Text.Json;
DateOnly specificDate = new DateOnly(2024, 5, 10);
string json = JsonSerializer.Serialize(specificDate);
DateOnly deserializedDate = JsonSerializer.Deserialize<DateOnly>(json);
Console.WriteLine(deserializedDate); // 05/10/2024
That’s a wrap!
So in conclusion DateOnly offers simplicity, readability, and consistency when working with dates in C# applications. By focusing on dates and ignoring time, it streamlines operations like database storage, user interfaces, and comparisons. Whether you're developing event management software, financial applications, or any other system reliant on dates, DateOnly can enhance your workflow and codebase.
I hope that this blog post was helpful and made you understand this datatype built into C#. If you have any questions or comments, feel free to reach out on @lovelacecoding on pretty much every social media platform or leave a comment down below.
See ya!