Member-only story
DateOnly in C#
In C# 9.0 and later, the DateOnly structure is available in the System namespace. DateOnly is designed to represent a date without the time portion, providing a more efficient and accurate way to work with dates when you don’t need to consider time information. It’s an improvement over using the DateTime structure, which always includes time information
Features with dateonlt in C#:
Creating a DateOnly:
You can create a DateOnly instance to represent a specific date. It requires a year, month, and day as parameters:
Example
using System;
DateOnly date = new DateOnly(2023, 10, 31);
Accessing Date Components:
You can access various components of a DateOnly object, such as the year, month, and day:
Example
int year = date.Year; // 2023
int month = date.Month; // 10
int day = date.Day; // 31
String Formatting:
You can convert a DateOnly instance to a string using the ToString method or a custom format:
Example
string defaultFormatted = date.ToString(); // "2023-10-31"
string customFormatted = date.ToString("MM/dd/yyyy"); // "10/31/2023"