DEV Community

Cover image for Modern C# Development: Get Started with DateOnly
Lou Creemers
Lou Creemers

Posted on • Updated on

Modern C# Development: Get Started with DateOnly

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:

  1. 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.

  2. Database Operations:

    Working with databases that store date information without time becomes seamless with DateOnly.

  3. User Interfaces:

    In input forms or date pickers, where time is not important, DateOnly simplifies the user experience by focusing on just the date.

  4. Comparisons:

    DateOnly is a great pick if your logic involves comparing days between dates. It has methods built in to compare dates.

  5. Consistency in Codebase:

    For codebases that heavily rely on dates, using DateOnly throughout helps with consistency.

  6. 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
Enter fullscreen mode Exit fullscreen mode

If you want to initialize a DateOnly variable with today's date, you can use the ‘FromDateTime’ method:

DateOnly today = DateOnly.FromDateTime(DateTime.Now);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Serialization

Serialization is often crucial when dealing with dates in applications. DateOnly simplifies this process. For instance, when working with JSON (don't forget to add the JSON package!):

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
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (6)

Collapse
 
michaeltharrington profile image
Michael Tharrington

Great post, Lou! 🙌

I noticed that this one and the last one ya shared both have the heading "Modern C#" and I figured you might enjoy making use of our series functionality...

We have a built-in feature that allows folks to create a series on DEV. If you're interested, here's an article that explains how:

And speaking of series, you might enjoy checking out the series 😉 that this article is a part of... it's called Best Practices for Writing on DEV and has lots of great guidance for writing on DEV.

Hope this info is helpful and thanks for sharing this post! Also, def don't feel obligated to put them in a series if you'd prefer to keep things as is. It's totally up to you! 🙂

Collapse
 
lovelacecoding profile image
Lou Creemers

That's so cool. Didn't know that functionality existed on here. I'll definitely check it out because I am planning on making this a series. Thanks 👍

Collapse
 
michaeltharrington profile image
Michael Tharrington

Sweet! No problemo. Happy to help out! 🙌

Collapse
 
incrementis profile image
Akin C. • Edited

Hello Lou Creemers,

thank you for your article.
It is very easy to read and therefore reading felt straightforward and quick which is amazing in my opinion.

I would like to point out a few things that might help improve your article:

Console.WriteLine(date); // [day]/[month]/[year] of today
may need to be fixed on:
Console.WriteLine(today); // [day]/[month]/[year] of today
as “date” was never declared and initialized.

Using new JapaneseCalendar() required this in my test using System.Globalization;

Using JsonSerializer.Deserialize<DateOnly>(json) required this in my test using System.Text.Json;

Additionally, I would recommend adding which .NET version you used, e.g. .NET 4.7.2 didn't work when I tested the code on .NET Fiddle, but the latest .NET 8 works.

I understand that these things may sound a bit trivial, but I would like to remind you that this article is for beginners and a beginner will find it difficult to understand why things are not working for him/her.
I would like to share this article on Twitter, but unfortunately that is not possible in the current state.

Collapse
 
lovelacecoding profile image
Lou Creemers

Thanks for the feedback. I'll alter it 🙏

Collapse
 
lovelacecoding profile image
Lou Creemers

Fixed! Thanks again ❤️