TimeOnly in C# with Examples

Shahzad Aslam
3 min readFeb 3, 2024

The TimeOnly in C# is available in the System namespace. TimeOnly in C# is designed to represent a time of day without the date portion, providing a more efficient and accurate way to work with time when you don’t need to consider the date. TimeOnly in C# is an improvement over using the DateTime structure, which always includes date information.

TimeOnly in C#

Features with TimeOnly in C#:

Creating a TimeOnly in C#:

You can create a TimeOnly instance to represent a specific time of day. It requires hours and minutes as parameters:

using System;
TimeOnly time = new TimeOnly(14, 30, 26);

Accessing TimeOnly Components in C#:

You can access the hour and minute components of a TimeOnly object:

int hour = time.Hour; // 14
int minute = time.Minute; // 30
int second = time.Second; // 26

TimeOnly ToString in C#

You can convert a TimeOnly instance to a string using the ToString method or a custom format:

string defaultFormatted = time.ToString(); // "14:30:00"
string customFormatted = time.ToString("hh:mm tt"); // "02:30 PM"

Arithmetic Operations of TimeOnly in C#:

--

--

Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.