Parsing Time Strings in C#: Converting "07:35" to TimeSpan and TimeOnly

Dec 02, 2025 · Programming · 10 views · 7.8

Keywords: C# | Time Parsing | TimeSpan | TimeOnly | String Conversion

Abstract: This article provides an in-depth exploration of methods for converting 24-hour time strings (such as "07:35") to time types in C#. It begins by analyzing three data types—TimeSpan, TimeOnly, and DateTime—focusing on their respective use cases and differences, with particular attention to the TimeOnly type introduced in .NET 6. The article then details four parsing methods: Parse, TryParse, ParseExact, and TryParseExact, including the use of standard and custom format strings. Complete code examples demonstrate flexible and exact parsing under various cultural settings, along with best practices for error handling. Finally, it discusses performance optimization and backward compatibility considerations to help developers choose the most appropriate conversion strategy for their specific needs.

Data Type Selection

When processing time strings like "07:35", C# offers three primary data type options, each with specific design purposes and applicable scenarios.

TimeSpan Type

The TimeSpan type is primarily designed to represent time intervals or durations. Although it can also represent time-of-day values (especially before .NET 6), its core purpose is handling time spans. This type ranges from -10675199.02:48:05.4775808 to 10675199.02:48:05.4775807 and can represent both positive and negative time values. When the time exceeds 24 hours, TimeSpan represents it in terms of days, with the default string representation using a period to separate the days portion.

TimeOnly Type

TimeOnly is a new type introduced in .NET 6, specifically designed to represent time-of-day values without any date component. Its valid range is from 00:00:00.000000 to 23:59:59.9999999. For scenarios requiring pure time value handling, TimeOnly provides the most semantic representation. For older .NET frameworks, polyfill libraries such as Portable.System.DateTimeOnly can be considered.

DateTime Type

The DateTime type is mainly used to represent combinations of dates and times. Although it can also represent pure time values (by using arbitrary dates like 0001-01-01), this approach requires ignoring the date portion during usage. Before .NET 6, this method was commonly used to support AM/PM format parsing, but with the introduction of TimeOnly, this practice is no longer necessary.

Parsing Methods Explained

All three data types support similar parsing methods, but the specific implementations of format strings differ.

Basic Parsing Methods

Four core parsing methods provide different levels of control and error handling:

Format String Specifications

The choice of format strings depends on the target data type:

TimeOnly and DateTime Formats

These two types use standard or custom date and time format strings. For the string "07:35", the custom format "HH:mm" can be used for parsing in all cultures, including the invariant culture. The standard format "t" also supports parsing in many cultures.

TimeSpan Formats

TimeSpan uses specialized time span format strings. For "07:35", the custom format @"hh\:mm" (or "hh\\:mm") can be used for parsing in most cultures. Standard formats "c" or "g" also support this format.

Code Implementation Examples

The following examples demonstrate how to convert "07:35" to TimeSpan and TimeOnly types using different methods. It is recommended to include System and System.Globalization using statements in code files.

Flexible Parsing (Using Current Culture)

// TimeSpan parsing
TimeSpan duration = TimeSpan.Parse("07:35");

// TimeOnly parsing
TimeOnly time = TimeOnly.Parse("07:35");

Exact Parsing (High Performance, Using Invariant Culture)

// TimeSpan exact parsing
TimeSpan duration = TimeSpan.ParseExact("07:35", @"hh\:mm", 
CultureInfo.InvariantCulture);

// TimeOnly exact parsing
TimeOnly time = TimeOnly.ParseExact("07:35", "HH:mm", 
CultureInfo.InvariantCulture);

Validation-Based Flexible Parsing

// TimeSpan validation parsing
TimeSpan duration;
if (!TimeSpan.TryParse("07:35", out duration))
{
    // Handle validation error
}

// TimeOnly validation parsing
TimeOnly time;
if (!TimeOnly.TryParse("07:35", out time))
{
    // Handle validation error
}

Validation-Based Exact Parsing

// TimeSpan exact validation parsing
TimeSpan duration;
if (!TimeSpan.TryParseExact("07:35", @"hh\:mm", 
CultureInfo.InvariantCulture, out duration))
{
    // Handle validation error
}

// TimeOnly exact validation parsing
TimeOnly time;
if (!TimeOnly.TryParseExact("07:35", "HH:mm", 
CultureInfo.InvariantCulture, DateTimeStyles.None, out time))
{
    // Handle validation error
}

Best Practices and Considerations

When selecting parsing methods, the following factors should be considered:

Performance Considerations

ParseExact and TryParseExact methods generally perform better than their Parse counterparts because they do not need to attempt multiple formats. When the input format is known and fixed, exact parsing methods should be prioritized.

Cultural Setting Impact

Using the invariant culture (CultureInfo.InvariantCulture) ensures consistent parsing behavior across different systems. This is particularly important for scenarios requiring serialization or cross-system communication.

Error Handling Strategies

In production code, TryParse series methods should be preferred to avoid performance overhead from exceptions. Use Parse methods only when the input format is guaranteed to be valid and exception scenarios are acceptable.

Backward Compatibility

For projects needing to support older .NET versions, TimeSpan remains the primary choice for handling time values. As .NET 6 and later versions become more widespread, TimeOnly offers a more semantic alternative.

Conclusion

Converting 24-hour time strings to appropriate time types is a common task in C# development. By understanding the characteristics of different data types and the differences among parsing methods, developers can choose the most suitable conversion strategy for their specific needs. The introduction of TimeOnly provides a better option for handling pure time values, while TimeSpan remains valuable for backward compatibility or when dealing with time intervals. Regardless of the chosen method, proper error handling and consideration of cultural settings are key factors in ensuring code robustness.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.