Modern C# Development: Get Started with DateOnly
Tags: csharp, dotnet, beginners, tutorial
Published: 2024-04-30 18:36:37

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:

```csharp
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:

```csharp
DateOnly today = DateOnly.FromDateTime(DateTime.Now);
```

You can write it to the console like every other variable:

```csharp
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]:

```csharp
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:

```csharp
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):

```csharp
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:

```csharp
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:

```csharp
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:

```csharp
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 (don't forget to add the JSON package!):

```csharp
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!