TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# 24-Hour Time Formats

This C# DateTime tutorial uses special logic to handle 24-hour time parsing.

24-hour time formats. A 24-hour clock can be converted.

We can change this format to a DateTime structure for easier usage in a program. This is challenging if there are inconsistencies or invalid dates in your data—which often occur.

Example. First, this code is helpful when you have only the 24-hour time figure, and not a well-formed total date. Sometimes the DateTime parsing methods in the base class libraries aren't useful.

Note: We don't know the total time and just want to base the time on the present.

Here: You may be working on a program that receives 24-hour times from an interface, but you want to process them in DateTime format.

Class that helps with military times: C#

using System;

public static class MilitaryTime
{
    public static void WriteMilitaryTime(DateTime date)
    {
	//
	// Convert hours and minutes to 24-hour scale.
	//
	string value = date.ToString("HHmm");
	Console.WriteLine(value);
    }

    public static DateTime ParseMilitaryTime(string time, int year, int month, int day)
    {
	//
	// Convert hour part of string to integer.
	//
	string hour = time.Substring(0, 2);
	int hourInt = int.Parse(hour);
	if (hourInt >= 24)
	{
	    throw new ArgumentOutOfRangeException("Invalid hour");
	}
	//
	// Convert minute part of string to integer.
	//
	string minute = time.Substring(2, 2);
	int minuteInt = int.Parse(minute);
	if (minuteInt >= 60)
	{
	    throw new ArgumentOutOfRangeException("Invalid minute");
	}
	//
	// Return the DateTime.
	//
	return new DateTime(year, month, day, hourInt, minuteInt, 0);
    }
}

This method, the second in the above example, divides the military 24-hour time string and turns it into 2 substrings. Then, we use int.Parse to turn the two parts to integers. Finally, the new DateTime with the parameters is returned.

Tip: You will need to modify some aspects of the method, but the technique for using 24-hour string times is useful.

Example 2. Here we see code that takes the current DateTime with the Now property, which accesses the local system time. Next it calls the WriteMilitaryTime method. This simply uses the correct ToString format string.

Then: It uses the ParseMilitaryTime method to transform the time strings with hours and minutes in 24-hour format into valid DateTimes.

C# program that turns military times into DateTimes

using System;

class Program
{
    static void Main()
    {
	//
	// Copy the current time into DateTime struct.
	//
	DateTime now = DateTime.Now;
	//
	// Write time as military time.
	//
	MilitaryTime.WriteMilitaryTime(now);

	//
	// Example military times.
	//
	string[] militaryTimes = new string[]
	{
	    "0000",
	    "0400",
	    "0550",
	    "1330",
	    "1400",
	    "2100",
	    "2200",
	    "2350",
	};
	//
	// Parse and display the times as DateTimes.
	//
	foreach (string militaryTime in militaryTimes)
	{
	    DateTime time = MilitaryTime.ParseMilitaryTime(militaryTime, 2009, 4, 27);
	    Console.WriteLine(time);
	}
    }
}

Output

1142

4/27/2009 12:00:00 AM
4/27/2009 4:00:00 AM
4/27/2009 5:50:00 AM
4/27/2009 1:30:00 PM
4/27/2009 2:00:00 PM
4/27/2009 9:00:00 PM
4/27/2009 10:00:00 PM
4/27/2009 11:50:00 PM

The foreach-loop near the end of the program uses the time figures for April 27, 2009. This works because those figures indicate a valid DateTime. If you try to make a DateTime with an invalid figure, the constructor will fail.

24-hour times. First, 24-hour times are based on the scale for 0-23, and they are more logical and less error-prone because there is no difference between 11 AM and 11 PM. They are also shorter to write for this reason.

And: The United States still uses the 12-hour clock in user interfaces and programs.

24-hour clock: Wikipedia

DateTime.Parse. There are some problems with the DateTime parsing methods in the System namespace. First, they require all parts of the time to be present, and the default is an empty (zero) time.

Therefore: If you have several numbers, it is easier to use the DateTime constructor.

DateTime.Parse String Method

Note on punctuation. If your time format has a colon (two dots) in the middle of it, you can either change the second Substring call to avoid it with one greater offset, or remove the punctuation before using the method.

Summary. We constructed DateTimes from 24-hour based time strings. Because the main difference between military 24-hour time and 12-hour time is the hour figure, it makes sense to simply parse the string and then use the DateTime constructor.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf