How to Use DateOnly and TimeOnly in C#
In C#,
DateOnly represents a date without time, and TimeOnly represents a time without date. You can create instances using constructors or parsing strings, and use their methods to manipulate or display date or time values separately.Syntax
DateOnly stores only the date part (year, month, day). TimeOnly stores only the time part (hour, minute, second, millisecond).
You can create them using constructors or parse strings.
csharp
var date = new DateOnly(2024, 6, 15); var time = new TimeOnly(14, 30, 0); var parsedDate = DateOnly.Parse("2024-06-15"); var parsedTime = TimeOnly.Parse("14:30:00");
Example
This example shows how to create, display, and add days or hours using DateOnly and TimeOnly.
csharp
using System; class Program { static void Main() { DateOnly date = new DateOnly(2024, 6, 15); TimeOnly time = new TimeOnly(14, 30, 0); Console.WriteLine($"Date: {date}"); Console.WriteLine($"Time: {time}"); DateOnly nextDay = date.AddDays(1); TimeOnly nextHour = time.AddHours(1); Console.WriteLine($"Next day: {nextDay}"); Console.WriteLine($"Next hour: {nextHour}"); } }
Output
Date: 2024-06-15
Time: 14:30:00
Next day: 2024-06-16
Next hour: 15:30:00
Common Pitfalls
- Trying to use
DateOnlyorTimeOnlywhereDateTimeis expected can cause errors because they are different types. - They do not store timezone or offset information.
- Parsing strings must match expected formats or use culture settings.
csharp
/* Wrong: assigning DateOnly to DateTime */ // DateTime dt = new DateOnly(2024, 6, 15); // Error /* Right: convert DateOnly to DateTime */ DateOnly d = new DateOnly(2024, 6, 15); DateTime dt = d.ToDateTime(TimeOnly.MinValue);
Quick Reference
| Feature | DateOnly | TimeOnly |
|---|---|---|
| Represents | Date only (year, month, day) | Time only (hour, minute, second, ms) |
| Create with | new DateOnly(year, month, day) | new TimeOnly(hour, minute, second) |
| Parse from string | DateOnly.Parse("yyyy-MM-dd") | TimeOnly.Parse("HH:mm:ss") |
| Add time | AddDays(int days) | AddHours(int hours) |
| Convert to DateTime | ToDateTime(TimeOnly time) | ToDateTime(DateOnly date) |
Key Takeaways
Use DateOnly to work with dates without times and TimeOnly for times without dates.
Create instances using constructors or parse from strings matching the expected format.
DateOnly and TimeOnly do not include timezone info; use DateTime for full date-time with timezone.
Convert DateOnly or TimeOnly to DateTime when needed using ToDateTime method.
Be careful not to mix DateOnly/TimeOnly directly with DateTime without conversion.