Generate Random Times in C#
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: C#
What: Generate random times in C# using TimeSpan and Random. Covers 12-hour, 24-hour formats, and time validation for .NET testing.
Try it: Use our interactive Times generator or integrate this code into your C# application.
Generate random times in C# using TimeSpan and Random. Covers 12-hour, 24-hour formats, and time validation for .NET testing. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C++ , Ruby and Go or use our interactive web generator.
C# Code Example
using System;
using System.Linq;
public class TimeGenerator
{
private static readonly Random random = new Random();
// Generate random time (24-hour format HH:MM:SS)
public static TimeSpan RandomTime24()
{
int hour = random.Next(0, 24);
int minute = random.Next(0, 60);
int second = random.Next(0, 60);
return new TimeSpan(hour, minute, second);
}
// Generate random time as formatted string
public static string RandomTimeString()
{
var time = RandomTime24();
return time.ToString(@"hh\:mm\:ss");
}
// Generate random time (12-hour format with AM/PM)
public static string RandomTime12()
{
int hour = random.Next(1, 13);
int minute = random.Next(0, 60);
string ampm = random.Next(2) == 0 ? "AM" : "PM";
return $"{hour:D2}:{minute:D2} {ampm}";
}
// Generate random time within business hours (9 AM - 5 PM)
public static TimeSpan RandomBusinessTime()
{
int hour = random.Next(9, 18); // 9-17
int minute = random.Next(0, 60);
return new TimeSpan(hour, minute, 0);
}
// Validate time string (HH:MM:SS)
public static bool IsValidTime(string time)
{
return TimeSpan.TryParse(time, out _);
}
// Generate multiple random times
public static TimeSpan[] GenerateTimes(int count = 10)
{
return Enumerable.Range(0, count)
.Select(_ => RandomTime24())
.ToArray();
}
public static void Main()
{
Console.WriteLine($"24-hour: {RandomTimeString()}");
Console.WriteLine($"12-hour: {RandomTime12()}");
Console.WriteLine($"Business: {RandomBusinessTime()}");
Console.WriteLine($"Valid: {IsValidTime(\"14:30:45\")}");
Console.WriteLine($"Batch: {string.Join(\", \", GenerateTimes(3))}");
}
}
[EXPLANATION]
C# uses TimeSpan to represent time durations or time-of-day. Random.Next() generates hours (0-23), minutes (0-59), seconds (0-59). TimeSpan(hour, minute, second) constructor creates time. String interpolation with :D2 adds leading zeros. ToString(@"hh\:mm\:ss") formats with custom pattern. TimeSpan.TryParse() validates time strings.
Expected Output
24-hour: 14:23:45 12-hour: 09:15 AM Business: 11:30:00 Valid: True Batch: 08:45:12, 16:20:33, 22:10:05
Common Use Cases
- Generate times for ASP.NET Core scheduling tests
- Create time fields for Entity Framework testing
- Generate appointment times for booking systems
- Test time validation in .NET web applications
- Create working hours for employee management
Important Notes
-
TimeSpanrepresents a time interval, often used for time-of-day -
:D2format specifier pads integers with leading zeros -
@"hh\:mm\:ss"uses verbatim string to escape colons -
TimeSpan.TryParse()returns bool without throwing exceptions -
Use
DateTime.TimeOfDayto extract time from DateTime
Try Our Interactive Generator
Don't want to write code? Use our free web-based Times generator with instant results.
TRY TIMES GENERATOR →Other Programming Languages
View Times generation code examples in PHP
View Times generation code examples in JavaScript
View Times generation code examples in Python
View Times generation code examples in Java
View Times generation code examples in C++
View Times generation code examples in Ruby
View Times generation code examples in Go