Introduction to DateOnly and TimeOnly in C#

Table Of Contents
Introduction
.NET 6 introduced two new value types: DateOnly and TimeOnly. Before these were available, developers often resorted to using DateTime for both date-only and time-related needs, which could lead to complexities and errors. These new structures streamline date and time handling by focusing only on the necessary components.
DateOnly
DateOnly represents a date without a time-of-day component. It’s useful when you only need to track a date, like a birthday or an anniversary.
TimeOnly
TimeOnly represents a time-of-day without a date component. This is great for scenarios like setting up a daily alarm or a meeting time.
Usage Examples
In practical scenarios, the relevance of these types goes beyond their syntactic utility. They cater to genuine use cases in our daily coding tasks. Let’s dive into how and why.
DateOnly
DateOnly is an efficient way to represent calendar dates without the complications of time zones or time-of-day considerations. This can be pivotal in scenarios like booking systems, calendars, or birthday reminders.
// Create a DateOnly instanceDateOnly today = DateOnly.Today;// Convert DateTime to DateOnlyDateTime dateTime = DateTime.Now;DateOnly date = DateOnly.FromDateTime(dateTime);// Parse from stringDateOnly anniversary = DateOnly.Parse("2023-10-02");Console.WriteLine($"Today's date: {today}");Console.WriteLine($"Parsed date: {anniversary}");
TimeOnly
Conversely, TimeOnly shines in use cases where you’re only interested in the time component. This can be in scenarios like scheduling alarms, recurrent meeting times, or shift timings in a 24-hour cycle.
// Create a TimeOnly instanceTimeOnly now = TimeOnly.Now;// Convert DateTime to TimeOnlyDateTime currentDateTime = DateTime.Now;TimeOnly time = TimeOnly.FromDateTime(currentDateTime);// Parse from stringTimeOnly meetingTime = TimeOnly.Parse("14:30"); // 2:30 PMConsole.WriteLine($"Current time: {now}");Console.WriteLine($"Parsed time: {meetingTime}");
JSON Serialization
To work with these new types in JSON serialization, especially if you are using System.Text.Json, you might need custom converters since, at the time of my last update, native support was still missing.
JSON Serialization Using System.Text.Json
using System;using System.Text.Json;using System.Text.Json.Serialization;public class DateOnlyConverter : JsonConverter<DateOnly>{public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options){return DateOnly.Parse(reader.GetString());}public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options){writer.WriteStringValue(value.ToString());}}public class TimeOnlyConverter : JsonConverter<TimeOnly>{public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options){return TimeOnly.Parse(reader.GetString());}public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options){writer.WriteStringValue(value.ToString());}}// Usage:string jsonData = @"{""date"": ""2023-10-02"",""time"": ""14:30""}";var options = new JsonSerializerOptions();options.Converters.Add(new DateOnlyConverter());options.Converters.Add(new TimeOnlyConverter());var data = JsonSerializer.Deserialize<MyClass>(jsonData, options);Console.WriteLine($"Date: {data.Date}, Time: {data.Time}");public class MyClass{public DateOnly Date { get; set; }public TimeOnly Time { get; set; }}
Conclusion
The introduction of DateOnly and TimeOnly structures in .NET 6 is a testament to the evolution of C#. They tackle the intricacies of date and time management, ensuring cleaner code and reduced chances of errors. As developers, adapting to these new features not only enhances our toolset but also optimizes application performance. Dive into your projects, give these types a spin, and see the difference for yourself!
For those wanting to delve deeper into the newer features of C# and .NET, Microsoft’s official documentation is invaluable. If you found this guide helpful, please consider sharing it with fellow developers and coding enthusiasts!
Feedback and Questions
Your insights drive us! For any questions, feedback, or thoughts, feel free to connect:
- Email: shady@shadynagy.com
- Twitter: @ShadyNagy_
- LinkedIn: Shady Nagy
- GitHub: ShadyNagy
If you found this guide beneficial, don’t hesitate to share it with your network and help others discover these useful features in C#.
Until the next guide, happy coding!







