▶ Random Everything - 100+ Free Generators // v2.8.5
root@generate-random:~/times/code-examples$ _

Random Time Code Examples

Random times of day in 24-hour and 12-hour formats in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

Every example below draws a time of day as HH:MM:SS on the 24-hour clock, the same as hh:MM AM/PM on the 12-hour clock, a time inside business hours, and validates a time string. The guide covers how a clock time maps to the 86,400 seconds of a day, how the two clock formats convert, and why some local times do not exist at all. Prefer no code? The interactive Times generator does the same in the browser.

A time of day is a number from 0 to 86,399

A day on the clock has 24 × 60 × 60 = 86,400 seconds. Drawing the hour from 0–23, the minute from 0–59 and the second from 0–59 independently, as the examples do, gives every one of those seconds the same chance; so does drawing one integer from 0 to 86,399 and splitting it with division and remainder (h = n / 3600, m = n % 3600 / 60, s = n % 60). For windows the single integer is handier: 09:00 to 17:00 is seconds 32,400 to 61,199.

Windows are where off-by-one errors hide: drawing the hour from 9 to 17 and then any minute yields times up to 17:59. The business-hours functions here draw hours 9 to 16, covering 09:00 to 16:59.

12-hour and 24-hour clocks

The 12-hour clock has no hour 0: it runs 12, 1, 2 … 11, twice a day. Midnight is 12:00 AM and noon is 12:00 PM, which is the conversion people get wrong most often. From 24-hour to 12-hour: h12 = (h24 % 12) || 12, with AM for hours 0–11 and PM for 12–23. Back again: h24 = h12 % 12 + (pm ? 12 : 0). An hour from 1–12 plus a fair AM/PM coin covers all 24 hours evenly.

Patterns differ: HH is the 0–23 hour in Java and .NET (H in PHP), hh the 1–12 hour; C, Python and Ruby use %H, %I and %p; Go writes 15 or 03. AM/PM text follows the locale.

Time zones and the hours that do not exist

A bare time like 02:30 has no zone, which is fine for opening hours or a form field. Attached to a date in a zone with daylight saving time, it can break. In the United States clocks jump from 02:00 to 03:00 on the second Sunday of March, so 02:00–02:59 never happens that day; on the first Sunday of November 01:00–01:59 happens twice. The European Union switches at 01:00 UTC on the last Sundays of March and October. A random time placed on those days is either invalid or ambiguous.

Libraries resolve this differently. Java ZonedDateTime.of moves a gap time forward by the gap length and picks the earlier offset in an overlap; Python zoneinfo uses the fold attribute to choose between the two 01:30s; Go time.Date returns one of the two candidate times without saying which. If the time will be stored as an instant, generate it in UTC. Offsets are not always whole hours, either: India is UTC+05:30, Nepal UTC+05:45.

Does it need a secure generator?

No. Appointment slots and shift starts reveal nothing, so Math.random(), mt_rand() or random are fine. So are random delays such as retry jitter or cron jobs spread over an hour: they need spread, not unpredictability.

Common mistakes

  • Accepting single-digit hours by accident. The pattern [01]?[0-9] in the validators accepts 9:30:45 as well as 09:30:45; drop the ? if you need exactly two digits.
  • Using a duration type as a clock time. A duration can exceed 24 hours, so a duration parser may accept "14" as fourteen days. Validate against an exact HH:MM:SS format.
  • Second 60. UTC has inserted 27 leap seconds as 23:59:60, the last at the end of 2016. Most time types reject a seconds value of 60; generate it only to test a parser.
  • Sorting formatted strings. HH:MM:SS strings sort correctly, but 12-hour strings do not: "01:15 PM" sorts before "11:40 AM".

Common Use Cases

  • Appointment and booking slots for scheduling system tests
  • Shift starts and working hours for staff and time-tracking apps
  • Test input for time pickers, form validation and time parsers
  • Time fields for Laravel, Django, Rails, JPA and Entity Framework models
  • Clock times for spreading cron jobs, reminders or retries across a window

Random Time Code Examples in PHP

Generate random times in PHP using mt_rand() and date() functions. Covers 12-hour, 24-hour formats, business hours, and time validation.

<?php
// Generate random time (24-hour format HH:MM:SS)
function randomTime24() {
    $hour = mt_rand(0, 23);
    $minute = mt_rand(0, 59);
    $second = mt_rand(0, 59);
    return sprintf("%02d:%02d:%02d", $hour, $minute, $second);
}

// Generate random time (12-hour format with AM/PM)
function randomTime12() {
    $hour = mt_rand(1, 12);
    $minute = mt_rand(0, 59);
    $ampm = mt_rand(0, 1) ? "AM" : "PM";
    return sprintf("%02d:%02d %s", $hour, $minute, $ampm);
}

// Generate random time within business hours (9 AM - 5 PM)
function randomBusinessTime() {
    $hour = mt_rand(9, 16);
    $minute = mt_rand(0, 59);
    return sprintf("%02d:%02d", $hour, $minute);
}

// Generate random time with seconds
function randomTimeWithSeconds() {
    return sprintf("%02d:%02d:%02d", mt_rand(0, 23), mt_rand(0, 59), mt_rand(0, 59));
}

// Validate time format (HH:MM:SS)
function isValidTime($time) {
    return preg_match("/^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/", $time) === 1;
}

// Generate multiple random times
function generateTimes($count = 10) {
    $times = [];
    for ($i = 0; $i < $count; $i++) {
        $times[] = randomTime24();
    }
    return $times;
}

echo "24-hour: " . randomTime24() . "\n";
echo "12-hour: " . randomTime12() . "\n";
echo "Business: " . randomBusinessTime() . "\n";
echo "Valid: " . (isValidTime("14:30:45") ? "true" : "false") . "\n";
echo "Batch: " . implode(", ", generateTimes(3)) . "\n";
?>

How it works in PHP

PHP uses mt_rand() to generate random hours (0-23), minutes (0-59), and seconds (0-59). sprintf("%02d") formats with leading zeros. Hours range from 0-23 for 24-hour format or 1-12 for 12-hour format with AM/PM. Business hours typically 9-17 (9 AM - 5 PM). preg_match() validates time format. Time components are independent of dates and timezones.

Sample output

24-hour: 14:23:45
12-hour: 09:15 AM
Business: 11:30
Valid: true
Batch: 08:45:12, 16:20:33, 22:10:05

PHP notes

  • mt_rand($min, $max) includes both ends, so mt_rand(0, 59) covers every minute.
  • date('g:i A', $ts) prints a 12-hour time without a leading zero and date('H:i:s', $ts) a 24-hour one.
  • DateTime::createFromFormat('H:i:s', $s) parses a strict time; check DateTime::getLastErrors() for overflow such as 25:00:00, which it otherwise rolls into the next day.

Random Time Code Examples in JavaScript

Generate random times in JavaScript using Math.random() and string formatting. Covers 12-hour, 24-hour formats, and time validation.

// Generate random time (24-hour format HH:MM:SS)
function randomTime24() {
    const hour = Math.floor(Math.random() * 24);
    const minute = Math.floor(Math.random() * 60);
    const second = Math.floor(Math.random() * 60);
    return `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}`;
}

// Generate random time (12-hour format with AM/PM)
function randomTime12() {
    const hour = Math.floor(Math.random() * 12) + 1;
    const minute = Math.floor(Math.random() * 60);
    const ampm = Math.random() < 0.5 ? "AM" : "PM";
    return `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")} ${ampm}`;
}

// Generate random time within business hours (9 AM - 5 PM)
function randomBusinessTime() {
    const hour = Math.floor(Math.random() * 8) + 9; // 9-16, so 09:00-16:59
    const minute = Math.floor(Math.random() * 60);
    return `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
}

// Generate random time with seconds
function randomTimeWithSeconds() {
    return `${Math.floor(Math.random() * 24).toString().padStart(2, "0")}:${Math.floor(Math.random() * 60).toString().padStart(2, "0")}:${Math.floor(Math.random() * 60).toString().padStart(2, "0")}`;
}

// Validate time format (HH:MM:SS)
function isValidTime(time) {
    const pattern = /^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;
    return pattern.test(time);
}

// Generate multiple random times
function generateTimes(count = 10) {
    return Array.from({ length: count }, () => randomTime24());
}

console.log("24-hour:", randomTime24());
console.log("12-hour:", randomTime12());
console.log("Business:", randomBusinessTime());
console.log("Valid:", isValidTime("14:30:45"));
console.log("Batch:", generateTimes(3).join(", "));

How it works in JavaScript

JavaScript uses Math.random() to generate hours (0-23), minutes (0-59), and seconds (0-59). padStart(2, "0") adds leading zeros. Math.floor() converts floats to integers. Template literals provide clean string formatting. Hours range 0-23 for 24-hour or 1-12 for 12-hour with AM/PM. RegExp.test() validates time format. Array.from() enables functional batch generation.

Sample output

24-hour: 14:23:45
12-hour: 09:15 AM
Business: 11:30
Valid: true
Batch: 08:45:12, 16:20:33, 22:10:05

JavaScript notes

  • Math.floor(Math.random() * 24) gives 0–23 because Math.random() never returns 1.
  • new Intl.DateTimeFormat('en-US', { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }) forces the 24-hour clock regardless of the user's locale.
  • A Date always carries a date and zone; for a bare time, keep the string or seconds since midnight.

Random Time Code Examples in Python

Generate random times in Python using random.randint() and datetime.time. Covers 12-hour, 24-hour formats, and time validation.

import random
from datetime import time

# Generate random time (24-hour format HH:MM:SS)
def random_time_24():
    hour = random.randint(0, 23)
    minute = random.randint(0, 59)
    second = random.randint(0, 59)
    return f"{hour:02d}:{minute:02d}:{second:02d}"

# Generate random time (12-hour format with AM/PM)
def random_time_12():
    hour = random.randint(1, 12)
    minute = random.randint(0, 59)
    ampm = random.choice(["AM", "PM"])
    return f"{hour:02d}:{minute:02d} {ampm}"

# Generate random time within business hours (9 AM - 5 PM)
def random_business_time():
    hour = random.randint(9, 16)
    minute = random.randint(0, 59)
    return f"{hour:02d}:{minute:02d}"

# Generate random time as datetime.time object
def random_time_object():
    return time(
        hour=random.randint(0, 23),
        minute=random.randint(0, 59),
        second=random.randint(0, 59)
    )

# Validate time format (HH:MM:SS)
def is_valid_time(time_str):
    import re
    pattern = r"^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$"
    return re.match(pattern, time_str) is not None

# Generate multiple random times
def generate_times(count=10):
    return [random_time_24() for _ in range(count)]

print(f"24-hour: {random_time_24()}")
print(f"12-hour: {random_time_12()}")
print(f"Business: {random_business_time()}")
print(f"Time object: {random_time_object()}")
print(f"Valid: {is_valid_time('14:30:45')}")
print("Batch:", ", ".join(generate_times(3)))

How it works in Python

Python uses random.randint() for hours (0-23), minutes (0-59), and seconds (0-59). F-string formatting with :02d adds leading zeros. datetime.time creates time objects with hour, minute, second parameters. random.choice() selects AM/PM. re.match() validates format. List comprehensions provide concise batch generation. Time objects are independent of dates.

Sample output

24-hour: 14:23:45
12-hour: 09:15 AM
Business: 11:30
Time object: 14:23:45
Valid: True
Batch: 08:45:12, 16:20:33, 22:10:05

Python notes

  • datetime.time is the time-of-day type; time(24, 0) and second=60 raise ValueError.
  • strftime('%I:%M %p') prints the 12-hour form; %p follows the locale, so output can differ from "AM"/"PM".
  • datetime.combine(d, t, tzinfo=ZoneInfo('America/New_York')) attaches a date and zone; set fold=1 on the time to get the second occurrence of a repeated hour.

Random Time Code Examples in Java

Generate random times in Java using LocalTime and Random. Covers 12-hour, 24-hour formats, and time validation for testing.

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TimeGenerator {
    private static final Random random = new Random();

    // Generate random time (24-hour format HH:MM:SS)
    public static LocalTime randomTime24() {
        int hour = random.nextInt(24);
        int minute = random.nextInt(60);
        int second = random.nextInt(60);
        return LocalTime.of(hour, minute, second);
    }

    // Generate random time as formatted string
    public static String randomTimeString() {
        LocalTime time = randomTime24();
        return time.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    }

    // Generate random time (12-hour format with AM/PM)
    public static String randomTime12() {
        int hour = random.nextInt(12) + 1;
        int minute = random.nextInt(60);
        String ampm = random.nextBoolean() ? "AM" : "PM";
        return String.format("%02d:%02d %s", hour, minute, ampm);
    }

    // Generate random time within business hours (9 AM - 5 PM)
    public static LocalTime randomBusinessTime() {
        int hour = random.nextInt(8) + 9; // 9-16, so 09:00-16:59
        int minute = random.nextInt(60);
        return LocalTime.of(hour, minute);
    }

    // Validate time string (HH:MM:SS)
    public static boolean isValidTime(String time) {
        try {
            LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm:ss"));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // Generate multiple random times
    public static List<LocalTime> generateTimes(int count) {
        List<LocalTime> times = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            times.add(randomTime24());
        }
        return times;
    }

    public static void main(String[] args) {
        System.out.println("24-hour: " + randomTimeString());
        System.out.println("12-hour: " + randomTime12());
        System.out.println("Business: " + randomBusinessTime());
        System.out.println("Valid: " + isValidTime("14:30:45"));
        System.out.println("Batch: " + generateTimes(3));
    }
}

How it works in Java

Java uses LocalTime.of(hour, minute, second) to create time objects. Random.nextInt(bound) generates hours (0-23), minutes (0-59), seconds (0-59). DateTimeFormatter formats output. String.format("%02d") adds leading zeros. LocalTime.parse() validates time strings. Java 8+ time API is preferred over legacy Date. LocalTime is immutable and thread-safe.

Sample output

24-hour: 14:23:45
12-hour: 09:15 AM
Business: 11:30
Valid: true
Batch: [08:45:12, 16:20:33, 22:10:05]

Java notes

  • LocalTime is a time with no date or zone; LocalTime.ofSecondOfDay(random.nextInt(86_400)) draws a uniform time in one call.
  • DateTimeFormatter.ofPattern("hh:mm a", Locale.US) prints the 12-hour form; without Locale.US the AM/PM text follows the JVM locale.
  • Prefer ThreadLocalRandom.current() over a shared Random when generating from several threads.

Random Time Code Examples in C#

Generate random times in C# using TimeSpan and Random. Covers 12-hour, 24-hour formats, and time validation for .NET testing.

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, 17); // 9-16, so 09:00-16:59
        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.TryParseExact(time, @"hh\:mm\:ss", null, 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))}");
    }
}

How it works in C#

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.

Sample 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

C# notes

  • Random.Next(min, max) excludes max: Next(0, 24) gives 0–23.
  • On .NET 6+, TimeOnly is the time-of-day type (new TimeOnly(h, m, s), ToString("hh:mm tt")); TimeSpan is a duration and can exceed 24 hours.
  • In a TimeSpan custom format the colons must be escaped (@"hh\:mm\:ss"), and hh there means hours 0–23, not the 12-hour clock.

Random Time Code Examples in C++

Generate random times in C++ using std::chrono and std::random. Covers time generation, formatting, and validation.

#include <iostream>
#include <random>
#include <iomanip>
#include <sstream>
#include <vector>
#include <chrono>

class TimeGenerator {
private:
    std::mt19937 rng;
    std::uniform_int_distribution<int> hourDist;
    std::uniform_int_distribution<int> minuteDist;
    std::uniform_int_distribution<int> secondDist;

public:
    TimeGenerator()
        : rng(std::random_device{}()),
          hourDist(0, 23),
          minuteDist(0, 59),
          secondDist(0, 59) {}

    // Generate random time (24-hour format HH:MM:SS)
    std::string randomTime24() {
        int hour = hourDist(rng);
        int minute = minuteDist(rng);
        int second = secondDist(rng);

        std::ostringstream oss;
        oss << std::setw(2) << std::setfill('0') << hour << ":"
            << std::setw(2) << std::setfill('0') << minute << ":"
            << std::setw(2) << std::setfill('0') << second;
        return oss.str();
    }

    // Generate random time (12-hour format with AM/PM)
    std::string randomTime12() {
        std::uniform_int_distribution<int> hour12Dist(1, 12);
        int hour = hour12Dist(rng);
        int minute = minuteDist(rng);
        std::string ampm = (rng() % 2 == 0) ? "AM" : "PM";

        std::ostringstream oss;
        oss << std::setw(2) << std::setfill('0') << hour << ":"
            << std::setw(2) << std::setfill('0') << minute << " " << ampm;
        return oss.str();
    }

    // Generate random time within business hours (9 AM - 5 PM)
    std::string randomBusinessTime() {
        std::uniform_int_distribution<int> businessHourDist(9, 16);
        int hour = businessHourDist(rng);
        int minute = minuteDist(rng);

        std::ostringstream oss;
        oss << std::setw(2) << std::setfill('0') << hour << ":"
            << std::setw(2) << std::setfill('0') << minute;
        return oss.str();
    }

    // Validate time format (basic validation)
    bool isValidTime(const std::string& time) {
        if (time.length() != 8) return false;
        if (time[2] != ':' || time[5] != ':') return false;

        int hour = std::stoi(time.substr(0, 2));
        int minute = std::stoi(time.substr(3, 2));
        int second = std::stoi(time.substr(6, 2));

        return hour >= 0 && hour < 24 &&
               minute >= 0 && minute < 60 &&
               second >= 0 && second < 60;
    }

    // Generate multiple random times
    std::vector<std::string> generateTimes(int count) {
        std::vector<std::string> times;
        times.reserve(count);
        for (int i = 0; i < count; ++i) {
            times.push_back(randomTime24());
        }
        return times;
    }
};

int main() {
    TimeGenerator generator;

    std::cout << "24-hour: " << generator.randomTime24() << std::endl;
    std::cout << "12-hour: " << generator.randomTime12() << std::endl;
    std::cout << "Business: " << generator.randomBusinessTime() << std::endl;
    std::cout << "Valid: " << (generator.isValidTime("14:30:45") ? "true" : "false") << std::endl;

    auto batch = generator.generateTimes(3);
    std::cout << "Batch: ";
    for (size_t i = 0; i < batch.size(); ++i) {
        std::cout << batch[i];
        if (i < batch.size() - 1) std::cout << ", ";
    }
    std::cout << std::endl;

    return 0;
}

How it works in C++

C++ uses std::uniform_int_distribution for hours (0-23), minutes (0-59), seconds (0-59). std::ostringstream with std::setw(2) and std::setfill('0') formats with leading zeros. std::mt19937 provides quality random generation. std::chrono can represent time durations. Manual validation checks hour, minute, second ranges.

Sample output

24-hour: 14:23:45
12-hour: 09:15 AM
Business: 11:30
Valid: true
Batch: 08:45:12, 16:20:33, 22:10:05

C++ notes

  • Constructing the three uniform_int_distribution objects once in the constructor avoids rebuilding them on each call.
  • rng() % 2 is unbiased here because mt19937 outputs 32 bits and 2 divides 232; a std::bernoulli_distribution(0.5) states the intent more clearly.
  • C++20 std::chrono::hh_mm_ss splits a duration since midnight into hours, minutes and seconds, and std::format("{:%H:%M:%S}", t) formats it.

Random Time Code Examples in Ruby

Generate random times in Ruby using rand() and Time class. Covers 12-hour, 24-hour formats, and time validation for Rails testing.

require "time"

# Generate random time (24-hour format HH:MM:SS)
def random_time_24
  hour = rand(0..23)
  minute = rand(0..59)
  second = rand(0..59)
  format("%02d:%02d:%02d", hour, minute, second)
end

# Generate random time (12-hour format with AM/PM)
def random_time_12
  hour = rand(1..12)
  minute = rand(0..59)
  ampm = ["AM", "PM"].sample
  format("%02d:%02d %s", hour, minute, ampm)
end

# Generate random time within business hours (9 AM - 5 PM)
def random_business_time
  hour = rand(9..16)
  minute = rand(0..59)
  format("%02d:%02d", hour, minute)
end

# Generate random time as Time object (today with random time)
def random_time_object
  Time.new(2024, 1, 1, rand(0..23), rand(0..59), rand(0..59))
end

# Validate time format (HH:MM:SS)
def valid_time?(time_str)
  time_str.match?(/^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/)
end

# Generate multiple random times
def generate_times(count = 10)
  Array.new(count) { random_time_24 }
end

puts "24-hour: #{random_time_24}"
puts "12-hour: #{random_time_12}"
puts "Business: #{random_business_time}"
puts "Time object: #{random_time_object.strftime("%H:%M:%S")}"
puts "Valid: #{valid_time?("14:30:45")}"
puts "Batch: #{generate_times(3).join(", ")}"

How it works in Ruby

Ruby uses rand(0..23) for hours, minutes, seconds. format("%02d") or sprintf adds leading zeros. Array#sample randomly picks AM/PM. Time.new() creates Time objects with hour, minute, second. String#match? validates format. Array.new(count) { block } generates batches. Ranges are inclusive on both ends.

Sample output

24-hour: 14:23:45
12-hour: 09:15 AM
Business: 11:30
Time object: 14:23:45
Valid: true
Batch: 08:45:12, 16:20:33, 22:10:05

Ruby notes

  • Ruby has no time-of-day class in the standard library, so the example puts the time on a fixed date (2024-01-01) and formats only the clock part.
  • strftime('%I:%M %p') gives "02:05 PM", %-I drops the leading zero and %P gives lowercase "pm".
  • rand(0..23) includes 23, while rand(24) gives the same 0–23 range.

Random Time Code Examples in Go

Generate random times in Go using math/rand and time package. Covers time generation, formatting, and validation for testing.

package main

import (
    "fmt"
    "math/rand"
    "regexp"
    "time"
)

// Generate random time (24-hour format HH:MM:SS)
func randomTime24() string {
    hour := rand.Intn(24)
    minute := rand.Intn(60)
    second := rand.Intn(60)
    return fmt.Sprintf("%02d:%02d:%02d", hour, minute, second)
}

// Generate random time (12-hour format with AM/PM)
func randomTime12() string {
    hour := rand.Intn(12) + 1
    minute := rand.Intn(60)
    ampm := []string{"AM", "PM"}[rand.Intn(2)]
    return fmt.Sprintf("%02d:%02d %s", hour, minute, ampm)
}

// Generate random time within business hours (9 AM - 5 PM)
func randomBusinessTime() string {
    hour := rand.Intn(8) + 9 // 9-16, so 09:00-16:59
    minute := rand.Intn(60)
    return fmt.Sprintf("%02d:%02d", hour, minute)
}

// Generate random time as time.Time object (today with random time)
func randomTimeObject() time.Time {
    now := time.Now()
    return time.Date(
        now.Year(), now.Month(), now.Day(),
        rand.Intn(24), rand.Intn(60), rand.Intn(60), 0,
        time.Local,
    )
}

// Validate time format (HH:MM:SS)
func isValidTime(timeStr string) bool {
    pattern := `^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$`
    matched, _ := regexp.MatchString(pattern, timeStr)
    return matched
}

// Generate multiple random times
func generateTimes(count int) []string {
    times := make([]string, count)
    for i := 0; i < count; i++ {
        times[i] = randomTime24()
    }
    return times
}

func main() {
    fmt.Println("24-hour:", randomTime24())
    fmt.Println("12-hour:", randomTime12())
    fmt.Println("Business:", randomBusinessTime())
    fmt.Println("Time object:", randomTimeObject().Format("15:04:05"))
    fmt.Println("Valid:", isValidTime("14:30:45"))
    fmt.Print("Batch: ")
    batch := generateTimes(3)
    for i, t := range batch {
        fmt.Print(t)
        if i < len(batch)-1 {
            fmt.Print(", ")
        }
    }
    fmt.Println()
}

How it works in Go

Go uses rand.Intn() for hours (0-23), minutes (0-59), seconds (0-59). fmt.Sprintf("%02d") formats with leading zeros. time.Date() creates time.Time with specific time. Format("15:04:05") uses Go reference time for formatting. regexp.MatchString() validates format. make([]string, count) pre-allocates slices.

Sample output

24-hour: 14:23:45
12-hour: 09:15 AM
Business: 11:30
Time object: 14:23:45
Valid: true
Batch: 08:45:12, 16:20:33, 22:10:05

Go notes

  • Go layouts use the reference time: "15:04:05" for 24-hour and "03:04 PM" for 12-hour output.
  • time.Date in time.Local on a daylight saving switch day may return a time an hour away from the one drawn; use time.UTC when the exact clock value matters.
  • regexp.MatchString compiles the pattern on every call; keep a regexp.MustCompile package variable for repeated validation.

Try the Interactive Generator

Need values right now rather than code? The Times generator runs in the browser and exports to TXT, CSV or JSON.

OPEN THE TIMES GENERATOR →