C# Uptime TimeSpan Format

Format illustration

You want to display the uptime for a program in the C# language, and the format should be similar to that in Microsoft Windows. Although the TimeSpan type has a ToString method, you can use custom formatting with a format string.

Example

Note

First, the format demonstrated in this program is equivalent to that produced by the Uptime.exe program provided by Microsoft. The program first takes two DateTimes that are a specified distance apart, and then computes that distance and stores it in a TimeSpan. Next, a format string is used with substitution marks, and then the TimeSpan instance is used to populate those substitutions correctly.

This C# example program demonstrates how to display a string formatted like an uptime.

Program that demonstrates uptime format [C#]

using System;

class Program
{
    static void Main()
    {
	// Get two DateTime instances.
	DateTime now = DateTime.Now;
	DateTime later = now.Add(new TimeSpan(16, 4, 24, 47));

	// Take difference of the two DateTime instances.
	TimeSpan diff = later.Subtract(now);

	// Format string.
	const string format =
	    "{0} has been up for: {1} day(s), {2} hour(s), {3} minute(s), {4} second(s)";

	// Write uptime.
	Console.WriteLine(format,
	    "SYSTEMNAME",
	    diff.Days,
	    diff.Hours,
	    diff.Minutes,
	    diff.Seconds);
    }
}

Output

SYSTEMNAME has been up for: 16 day(s), 4 hour(s), 24 minute(s), 47 second(s)
Programming tip

Days versus TotalDays. In this context it is important to use the Days, Hours, Minutes and Seconds properties, not the Total properties, because the time is divided up and you are not representing it in only a single unit. Also, the code here does not dynamically add or remove the trailing "s" when required, but it is equivalent to the functionality of Uptime.exe.

Summary

In this article, we looked at a simple way to format a TimeSpan instance so that it is equivalent to the Uptime program provided by Microsoft. We do not use the default ToString method, and our approach here yields a string that is easier to read than the default string representation.

TimeSpan Examples Time Representations
.NET