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

Random Unix Timestamp Code Examples

Random epoch timestamps in seconds and milliseconds in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

The examples below read the current Unix time, draw a random timestamp between two dates or within N days of now, and convert it back to a readable date and time. The guide explains what the number counts, how to tell seconds from milliseconds at a glance, why 2038 still matters, and which text format to use when a timestamp leaves your program. Prefer no code? The interactive Timestamps generator does the same in the browser.

What a Unix timestamp counts

A Unix timestamp is the number of seconds since 1970-01-01T00:00:00Z, the epoch. It is the same number everywhere on Earth at the same instant: time zones only appear when you turn it into a calendar date and clock time. Unix time also ignores leap seconds; every day counts as exactly 86,400 seconds, so subtracting two timestamps gives elapsed time to within the 27 leap seconds inserted since 1972.

Because a timestamp is already an instant, a uniform draw over seconds is the natural choice here: random(start, end) with both bounds as epoch seconds. Take care with how the bounds are made. A date-only string such as "2024-12-31" becomes midnight at the start of that day, which silently drops the whole last day from the range; the examples extend the end bound to 23:59:59 so the range ends at the last second of the end date.

Seconds, milliseconds or more

Unix tools, PHP, Python, Ruby, Go and most SQL functions count seconds; JavaScript Date.now() and Java System.currentTimeMillis() count milliseconds; Go, Python and C++ can also give microseconds or nanoseconds. Mixing them up is the most common timestamp bug, and it is easy to spot by length: for any instant between 2001-09-09 and 2286-11-20, a seconds value has 10 digits and a milliseconds value has 13. Feed 13 digits to a seconds parser and you land more than 50,000 years in the future; feed 10 digits to a milliseconds parser and you land in January 1970.

Precision has limits too. A JavaScript number is a double that stores integers exactly only up to 253 − 1, enough for milliseconds but not for nanoseconds since 1970. A float from Python time.time() carries only about a quarter of a microsecond of resolution at today's values; use time.time_ns() for exact integers.

The 2038 limit

A signed 32-bit integer holds at most 2,147,483,647 seconds, which is 2038-01-19T03:14:07Z; one second later it wraps to −2,147,483,648, i.e. 1901-12-13T20:45:52Z. 64-bit runtimes are safe, but 32-bit builds, embedded code, file formats and databases still carry the limit: a MySQL TIMESTAMP column stops at 2038-01-19 03:14:07 UTC. Include test values past 2038, and before 1970 (negative numbers), on purpose.

Writing timestamps as text: ISO 8601 and RFC 3339

For APIs, logs and JSON, send either the integer with its unit named in the field (created_at_ms) or an RFC 3339 string such as 2024-12-31T23:59:59Z. RFC 3339 is a strict profile of ISO 8601: full date, full time and a mandatory offset (Z or +01:00). ISO 8601 also allows week dates and compact forms like 20241231T235959Z that many parsers reject. Always include the offset: without one, some parsers read local time and others UTC. RFC 9557 (2024) adds an optional bracketed zone name: …+01:00[Europe/Paris].

Security and common mistakes

  • Random test timestamps need no secure generator; jitter on cache expiry or token lifetimes in tests is fine with the default one.
  • The current time is a poor seed or secret. Seeding a generator with the clock (the old rand.Seed(time.Now().UnixNano()) idiom) means anyone who knows roughly when it ran can replay it. Tokens and nonces need the secure source; a timestamp inside an identifier such as UUIDv7 only orders values, the random bits provide the uniqueness.
  • Formatting in the server's zone. date(), localtime() and fromtimestamp() use the machine's zone, so the same timestamp prints differently on a laptop and in a container set to UTC.
  • Unsorted events. Independent random draws arrive in random order; sort them before writing a log or time series.

Common Use Cases

  • created_at and updated_at values for database seeding and fixtures
  • Log and audit entries for monitoring, parsing and retention tests
  • Expiry times for sessions, caches, JWT exp claims and TTL logic
  • Event streams for sorting, filtering, windowing and rate-limit tests
  • Edge values before 1970 and after 2038 for overflow and parser tests

Random Unix Timestamp Code Examples in PHP

Generate random Unix timestamps in PHP using time() and mt_rand(). Covers current time, past/future timestamps, date ranges, and formatting for testing.

<?php
// Generate current Unix timestamp
function currentTimestamp() {
    return time();
}

// Generate random timestamp between two dates
function randomTimestamp($startDate, $endDate) {
    $startTimestamp = strtotime($startDate);
    $endTimestamp = strtotime("$endDate 23:59:59"); // include the whole end day
    return mt_rand($startTimestamp, $endTimestamp);
}

// Generate random past timestamp (within N days)
function randomPastTimestamp($daysAgo = 365) {
    $now = time();
    $seconds = $daysAgo * 86400; // 86400 seconds in a day
    return mt_rand($now - $seconds, $now);
}

// Generate random future timestamp (within N days)
function randomFutureTimestamp($daysAhead = 365) {
    $now = time();
    $seconds = $daysAhead * 86400;
    return mt_rand($now, $now + $seconds);
}

// Convert timestamp to readable format
function formatTimestamp($timestamp, $format = "Y-m-d H:i:s") {
    return date($format, $timestamp);
}

// Generate multiple random timestamps
function generateTimestamps($count = 10, $startDate = "2020-01-01", $endDate = "2024-12-31") {
    $timestamps = [];
    for ($i = 0; $i < $count; $i++) {
        $timestamps[] = randomTimestamp($startDate, $endDate);
    }
    return $timestamps;
}

echo "Current: " . currentTimestamp() . "\n";
echo "Random: " . randomTimestamp("2023-01-01", "2024-12-31") . "\n";
echo "Past: " . randomPastTimestamp(30) . " (" . formatTimestamp(randomPastTimestamp(30)) . ")\n";
echo "Future: " . randomFutureTimestamp(30) . " (" . formatTimestamp(randomFutureTimestamp(30)) . ")\n";
echo "Batch: " . implode(", ", generateTimestamps(3)) . "\n";
?>

How it works in PHP

PHP uses time() for current Unix timestamp (seconds since January 1, 1970 UTC). strtotime() converts date strings to timestamps. mt_rand() generates random timestamps within ranges. date() formats timestamps for display. 86400 is the number of seconds in a day (24 * 60 * 60). Unix timestamps are timezone-independent integers, making them ideal for database storage and API communication.

Sample output

Current: 1703001234
Random: 1698765432
Past: 1700445678 (2023-11-19 14:27:58)
Future: 1706123456 (2024-01-24 18:10:56)
Batch: 1680123456, 1685432100, 1692345678

PHP notes

  • gmdate() formats in UTC; date() uses the date.timezone setting.
  • date(DATE_RFC3339, $ts) (format Y-m-d\TH:i:sP) prints an RFC 3339 string; DATE_RFC3339_EXTENDED adds milliseconds.
  • Timestamps past 2038 need a 64-bit build (PHP_INT_SIZE === 8); (new DateTimeImmutable('@' . $ts)) creates a UTC object from one.

Random Unix Timestamp Code Examples in JavaScript

Generate random Unix timestamps in JavaScript using Date.now() and Math.random(). Covers current time, past/future timestamps, and formatting for testing.

// Generate current Unix timestamp (milliseconds)
function currentTimestamp() {
    return Date.now();
}

// Generate current Unix timestamp (seconds)
function currentTimestampSeconds() {
    return Math.floor(Date.now() / 1000);
}

// Generate random timestamp between two dates
function randomTimestamp(startDate, endDate) {
    const start = new Date(startDate).getTime();
    const end = new Date(endDate).getTime() + 86400000 - 1; // include the whole end day
    return Math.floor(Math.random() * (end - start + 1)) + start;
}

// Generate random past timestamp (within N days)
function randomPastTimestamp(daysAgo = 365) {
    const now = Date.now();
    const milliseconds = daysAgo * 86400000; // 86400000 ms in a day
    return Math.floor(Math.random() * milliseconds) + (now - milliseconds);
}

// Generate random future timestamp (within N days)
function randomFutureTimestamp(daysAhead = 365) {
    const now = Date.now();
    const milliseconds = daysAhead * 86400000;
    return Math.floor(Math.random() * milliseconds) + now;
}

// Convert timestamp to readable format
function formatTimestamp(timestamp, locale = "en-US") {
    return new Date(timestamp).toLocaleString(locale);
}

// Generate multiple random timestamps
function generateTimestamps(count = 10, startDate = "2020-01-01", endDate = "2024-12-31") {
    return Array.from({ length: count }, () => randomTimestamp(startDate, endDate));
}

console.log("Current (ms):", currentTimestamp());
console.log("Current (s):", currentTimestampSeconds());
console.log("Random:", randomTimestamp("2023-01-01", "2024-12-31"));
console.log("Past:", randomPastTimestamp(30), "(" + formatTimestamp(randomPastTimestamp(30)) + ")");
console.log("Future:", randomFutureTimestamp(30), "(" + formatTimestamp(randomFutureTimestamp(30)) + ")");
console.log("Batch:", generateTimestamps(3).join(", "));

How it works in JavaScript

JavaScript Date.now() returns current timestamp in milliseconds (not seconds like Unix). new Date(dateString).getTime() converts dates to milliseconds. Math.random() generates random values within ranges. Math.floor() converts to integers. 86400000 is milliseconds per day. toLocaleString() formats for display. Divide by 1000 to convert JavaScript timestamps to Unix seconds for backend APIs.

Sample output

Current (ms): 1703001234567
Current (s): 1703001234
Random: 1698765432000
Past: 1700445678000 (11/19/2023, 2:27:58 PM)
Future: 1706123456000 (1/24/2024, 6:10:56 PM)
Batch: 1680123456000, 1685432100000, 1692345678000

JavaScript notes

  • Date.now() and getTime() are milliseconds; Math.floor(ms / 1000) gives the Unix seconds a backend usually expects.
  • A Date can hold ±8.64 × 1015 ms from the epoch (years −271,821 to 275,760); beyond that it is an Invalid Date.
  • toISOString() always prints UTC with milliseconds and a Z, which is valid RFC 3339; toLocaleString() output is for display only.

Random Unix Timestamp Code Examples in Python

Generate random Unix timestamps in Python using time.time() and random.randint(). Covers current time, past/future timestamps, and formatting for testing.

import random
import time
from datetime import datetime, timedelta

# Generate current Unix timestamp
def current_timestamp():
    return int(time.time())

# Generate random timestamp between two dates
def random_timestamp(start_date, end_date):
    start = datetime.strptime(start_date, "%Y-%m-%d").timestamp()
    end = datetime.strptime(end_date, "%Y-%m-%d").timestamp() + 86399  # through 23:59:59
    return int(random.uniform(start, end))

# Generate random past timestamp (within N days)
def random_past_timestamp(days_ago=365):
    now = time.time()
    seconds = days_ago * 86400
    return int(random.uniform(now - seconds, now))

# Generate random future timestamp (within N days)
def random_future_timestamp(days_ahead=365):
    now = time.time()
    seconds = days_ahead * 86400
    return int(random.uniform(now, now + seconds))

# Convert timestamp to readable format
def format_timestamp(timestamp, fmt="%Y-%m-%d %H:%M:%S"):
    return datetime.fromtimestamp(timestamp).strftime(fmt)

# Generate multiple random timestamps
def generate_timestamps(count=10, start_date="2020-01-01", end_date="2024-12-31"):
    return [random_timestamp(start_date, end_date) for _ in range(count)]

print(f"Current: {current_timestamp()}")
print(f"Random: {random_timestamp('2023-01-01', '2024-12-31')}")
past = random_past_timestamp(30)
print(f"Past: {past} ({format_timestamp(past)})")
future = random_future_timestamp(30)
print(f"Future: {future} ({format_timestamp(future)})")
print("Batch:", ", ".join(map(str, generate_timestamps(3))))

How it works in Python

Python time.time() returns current Unix timestamp as float (seconds with decimals). datetime.timestamp() converts datetime objects to timestamps. random.uniform() generates float in range. int() converts to integer timestamps. datetime.fromtimestamp() converts back to datetime. strftime() formats for display. Use datetime.fromtimestamp(ts, tz=timezone.utc) for UTC time (utcfromtimestamp() is deprecated since Python 3.12).

Sample output

Current: 1703001234
Random: 1698765432
Past: 1700445678 (2023-11-19 14:27:58)
Future: 1706123456 (2024-01-24 18:10:56)
Batch: 1680123456, 1685432100, 1692345678

Python notes

  • datetime.timestamp() on a naive datetime assumes local time, which is why random_timestamp depends on the machine's zone; build bounds with tzinfo=timezone.utc for zone-independent results.
  • datetime.fromtimestamp(ts, tz=timezone.utc).isoformat() prints +00:00 rather than Z; fromisoformat() accepts Z since Python 3.11.
  • time.time_ns() (Python 3.7+) returns an exact integer in nanoseconds.

Random Unix Timestamp Code Examples in Java

Generate random Unix timestamps in Java using System.currentTimeMillis() and Random. Covers current time, past/future timestamps, and formatting for testing.

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

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

    // Generate current Unix timestamp (seconds)
    public static long currentTimestamp() {
        return Instant.now().getEpochSecond();
    }

    // Generate current Unix timestamp (milliseconds)
    public static long currentTimestampMillis() {
        return System.currentTimeMillis();
    }

    // Generate random timestamp between two dates
    public static long randomTimestamp(String startDate, String endDate) {
        long start = LocalDateTime.parse(startDate + "T00:00:00")
            .atZone(ZoneId.systemDefault()).toEpochSecond();
        long end = LocalDateTime.parse(endDate + "T23:59:59")
            .atZone(ZoneId.systemDefault()).toEpochSecond();
        return ThreadLocalRandom.current().nextLong(start, end + 1);
    }

    // Generate random past timestamp (within N days)
    public static long randomPastTimestamp(int daysAgo) {
        long now = Instant.now().getEpochSecond();
        long seconds = daysAgo * 86400L;
        return now - ThreadLocalRandom.current().nextLong(0, seconds);
    }

    // Generate random future timestamp (within N days)
    public static long randomFutureTimestamp(int daysAhead) {
        long now = Instant.now().getEpochSecond();
        long seconds = daysAhead * 86400L;
        return now + ThreadLocalRandom.current().nextLong(0, seconds);
    }

    // Convert timestamp to readable format
    public static String formatTimestamp(long timestamp) {
        return LocalDateTime.ofInstant(
            Instant.ofEpochSecond(timestamp),
            ZoneId.systemDefault()
        ).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    // Generate multiple random timestamps
    public static List<Long> generateTimestamps(int count, String startDate, String endDate) {
        List<Long> timestamps = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            timestamps.add(randomTimestamp(startDate, endDate));
        }
        return timestamps;
    }

    public static void main(String[] args) {
        System.out.println("Current: " + currentTimestamp());
        System.out.println("Random: " + randomTimestamp("2023-01-01", "2024-12-31"));
        long past = randomPastTimestamp(30);
        System.out.println("Past: " + past + " (" + formatTimestamp(past) + ")");
        long future = randomFutureTimestamp(30);
        System.out.println("Future: " + future + " (" + formatTimestamp(future) + ")");
        System.out.println("Batch: " + generateTimestamps(3, "2023-01-01", "2024-12-31"));
    }
}

How it works in Java

Java Instant.now().getEpochSecond() returns current Unix timestamp in seconds. System.currentTimeMillis() returns milliseconds since epoch. ThreadLocalRandom is thread-safe for concurrent generation. LocalDateTime.parse() parses dates, atZone() adds timezone. DateTimeFormatter formats output. Java 8+ time API (java.time) is preferred over legacy Date class.

Sample output

Current: 1703001234
Random: 1698765432
Past: 1700445678 (2023-11-19 14:27:58)
Future: 1706123456 (2024-01-24 18:10:56)
Batch: [1680123456, 1685432100, 1692345678]

Java notes

  • Instant is the timestamp type: Instant.ofEpochSecond() and Instant.ofEpochMilli() build one, and toString() prints ISO 8601 in UTC.
  • ThreadLocalRandom.nextLong(origin, bound) excludes bound, hence end + 1.
  • The example uses ZoneId.systemDefault() for its bounds and output; pass ZoneOffset.UTC to get the same numbers on every machine.

Random Unix Timestamp Code Examples in C#

Generate random Unix timestamps in C# using DateTimeOffset and Random. Covers current time, past/future timestamps, and formatting for .NET testing.

using System;
using System.Linq;

public class TimestampGenerator
{
    private static readonly Random random = new Random();

    // Generate current Unix timestamp (seconds)
    public static long CurrentTimestamp()
    {
        return DateTimeOffset.UtcNow.ToUnixTimeSeconds();
    }

    // Generate current Unix timestamp (milliseconds)
    public static long CurrentTimestampMillis()
    {
        return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    }

    // Generate random timestamp between two dates
    public static long RandomTimestamp(string startDate, string endDate)
    {
        var start = DateTimeOffset.Parse(startDate).ToUnixTimeSeconds();
        var end = DateTimeOffset.Parse(endDate).AddDays(1).ToUnixTimeSeconds(); // through 23:59:59 of the end date
        return (long)(random.NextDouble() * (end - start)) + start;
    }

    // Generate random past timestamp (within N days)
    public static long RandomPastTimestamp(int daysAgo = 365)
    {
        var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        var seconds = daysAgo * 86400L;
        return now - (long)(random.NextDouble() * seconds);
    }

    // Generate random future timestamp (within N days)
    public static long RandomFutureTimestamp(int daysAhead = 365)
    {
        var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        var seconds = daysAhead * 86400L;
        return now + (long)(random.NextDouble() * seconds);
    }

    // Convert timestamp to readable format
    public static string FormatTimestamp(long timestamp)
    {
        return DateTimeOffset.FromUnixTimeSeconds(timestamp)
            .LocalDateTime.ToString("yyyy-MM-dd HH:mm:ss");
    }

    // Generate multiple random timestamps
    public static long[] GenerateTimestamps(int count = 10, string startDate = "2020-01-01", string endDate = "2024-12-31")
    {
        return Enumerable.Range(0, count)
            .Select(_ => RandomTimestamp(startDate, endDate))
            .ToArray();
    }

    public static void Main()
    {
        Console.WriteLine($"Current: {CurrentTimestamp()}");
        Console.WriteLine($"Random: {RandomTimestamp("2023-01-01", "2024-12-31")}");
        var past = RandomPastTimestamp(30);
        Console.WriteLine($"Past: {past} ({FormatTimestamp(past)})");
        var future = RandomFutureTimestamp(30);
        Console.WriteLine($"Future: {future} ({FormatTimestamp(future)})");
        Console.WriteLine($"Batch: {string.Join(", ", GenerateTimestamps(3))}");
    }
}

How it works in C#

C# DateTimeOffset.UtcNow.ToUnixTimeSeconds() returns current Unix timestamp. DateTimeOffset includes timezone information. Random.NextDouble() generates float for range calculations. DateTimeOffset.Parse() parses date strings. FromUnixTimeSeconds() converts back to DateTimeOffset. Use ToUnixTimeMilliseconds() for millisecond precision. Always use UTC for timestamp generation.

Sample output

Current: 1703001234
Random: 1698765432
Past: 1700445678 (2023-11-19 14:27:58)
Future: 1706123456 (2024-01-24 18:10:56)
Batch: 1680123456, 1685432100, 1692345678

C# notes

  • DateTimeOffset.FromUnixTimeSeconds(), FromUnixTimeMilliseconds() and ToUnixTimeSeconds() convert in both directions; ToString("O") prints a round-trip ISO 8601 string.
  • On .NET 6+, Random.Shared.NextInt64(start, end + 1) draws a whole-second timestamp without going through NextDouble(), and is thread-safe.
  • DateTimeOffset.Parse("2024-12-31") uses the machine's local offset; use DateTimeOffset.ParseExact with DateTimeStyles.AssumeUniversal for UTC bounds.

Random Unix Timestamp Code Examples in C++

Generate random Unix timestamps in C++ using std::chrono and std::random. Covers current time, past/future timestamps, and formatting.

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

class TimestampGenerator {
private:
    std::mt19937_64 rng;

public:
    TimestampGenerator() : rng(std::random_device{}()) {}

    // Generate current Unix timestamp (seconds)
    int64_t currentTimestamp() {
        auto now = std::chrono::system_clock::now();
        return std::chrono::duration_cast<std::chrono::seconds>(
            now.time_since_epoch()
        ).count();
    }

    // Generate current Unix timestamp (milliseconds)
    int64_t currentTimestampMillis() {
        auto now = std::chrono::system_clock::now();
        return std::chrono::duration_cast<std::chrono::milliseconds>(
            now.time_since_epoch()
        ).count();
    }

    // Generate random timestamp between two Unix timestamps
    int64_t randomTimestamp(int64_t start, int64_t end) {
        std::uniform_int_distribution<int64_t> dist(start, end);
        return dist(rng);
    }

    // Generate random past timestamp (within N days)
    int64_t randomPastTimestamp(int daysAgo = 365) {
        int64_t now = currentTimestamp();
        int64_t seconds = daysAgo * 86400LL;
        std::uniform_int_distribution<int64_t> dist(now - seconds, now);
        return dist(rng);
    }

    // Generate random future timestamp (within N days)
    int64_t randomFutureTimestamp(int daysAhead = 365) {
        int64_t now = currentTimestamp();
        int64_t seconds = daysAhead * 86400LL;
        std::uniform_int_distribution<int64_t> dist(now, now + seconds);
        return dist(rng);
    }

    // Convert timestamp to readable format
    std::string formatTimestamp(int64_t timestamp) {
        std::time_t time = static_cast<std::time_t>(timestamp);
        std::tm* tm = std::localtime(&time);
        std::ostringstream oss;
        oss << std::put_time(tm, "%Y-%m-%d %H:%M:%S");
        return oss.str();
    }

    // Generate multiple random timestamps
    std::vector<int64_t> generateTimestamps(int count, int64_t start, int64_t end) {
        std::vector<int64_t> timestamps;
        timestamps.reserve(count);
        for (int i = 0; i < count; ++i) {
            timestamps.push_back(randomTimestamp(start, end));
        }
        return timestamps;
    }
};

int main() {
    TimestampGenerator generator;

    std::cout << "Current: " << generator.currentTimestamp() << std::endl;

    // 2023-01-01 to 2024-12-31 in Unix timestamps
    int64_t start = 1672531200; // 2023-01-01
    int64_t end = 1735689599;   // 2024-12-31
    std::cout << "Random: " << generator.randomTimestamp(start, end) << std::endl;

    int64_t past = generator.randomPastTimestamp(30);
    std::cout << "Past: " << past << " (" << generator.formatTimestamp(past) << ")" << std::endl;

    int64_t future = generator.randomFutureTimestamp(30);
    std::cout << "Future: " << future << " (" << generator.formatTimestamp(future) << ")" << std::endl;

    auto batch = generator.generateTimestamps(3, start, end);
    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++ std::chrono::system_clock::now() gets current time. time_since_epoch() converts to duration. duration_cast converts to seconds or milliseconds. std::uniform_int_distribution generates random values. std::put_time() formats timestamps. std::mt19937_64 provides 64-bit random generation for large timestamp ranges. Use std::gmtime() instead of localtime() for UTC.

Sample output

Current: 1703001234
Random: 1698765432
Past: 1700445678 (2023-11-19 14:27:58)
Future: 1706123456 (2024-01-24 18:10:56)
Batch: 1680123456, 1685432100, 1692345678

C++ notes

  • Since C++20, std::chrono::system_clock is specified to measure Unix time (excluding leap seconds); earlier standards left the epoch unspecified, although all major implementations used 1970.
  • std::gmtime and std::localtime share static storage; use gmtime_r or gmtime_s in threaded code.
  • std::mt19937_64 with uniform_int_distribution<int64_t> covers 64-bit ranges, including timestamps far past 2038.

Random Unix Timestamp Code Examples in Ruby

Generate random Unix timestamps in Ruby using Time.now and rand(). Covers current time, past/future timestamps, and formatting for Rails testing.

require "time"

# Generate current Unix timestamp
def current_timestamp
  Time.now.to_i
end

# Generate random timestamp between two dates
def random_timestamp(start_date, end_date)
  start_time = Time.parse(start_date).to_i
  end_time = Time.parse(end_date).to_i + 86_399 # through 23:59:59 of the end date
  rand(start_time..end_time)
end

# Generate random past timestamp (within N days)
def random_past_timestamp(days_ago = 365)
  now = Time.now.to_i
  seconds = days_ago * 86400
  rand((now - seconds)..now)
end

# Generate random future timestamp (within N days)
def random_future_timestamp(days_ahead = 365)
  now = Time.now.to_i
  seconds = days_ahead * 86400
  rand(now..(now + seconds))
end

# Convert timestamp to readable format
def format_timestamp(timestamp, format = "%Y-%m-%d %H:%M:%S")
  Time.at(timestamp).strftime(format)
end

# Generate multiple random timestamps
def generate_timestamps(count = 10, start_date = "2020-01-01", end_date = "2024-12-31")
  Array.new(count) { random_timestamp(start_date, end_date) }
end

puts "Current: #{current_timestamp}"
puts "Random: #{random_timestamp("2023-01-01", "2024-12-31")}"
past = random_past_timestamp(30)
puts "Past: #{past} (#{format_timestamp(past)})"
future = random_future_timestamp(30)
puts "Future: #{future} (#{format_timestamp(future)})"
puts "Batch: #{generate_timestamps(3).join(", ")}"

How it works in Ruby

Ruby Time.now.to_i returns current Unix timestamp (seconds). Time.parse() parses date strings to Time objects. rand(start..end) generates random integers in range. Time.at() converts timestamp to Time object. strftime() formats for display. 86400 is seconds per day. Use Time.utc() instead of Time.now for UTC timestamps.

Sample output

Current: 1703001234
Random: 1698765432
Past: 1700445678 (2023-11-19 14:27:58)
Future: 1706123456 (2024-01-24 18:10:56)
Batch: 1680123456, 1685432100, 1692345678

Ruby notes

  • Time.at(0, ms, :millisecond) builds a Time from milliseconds; Time.now.to_i gives seconds.
  • Time#iso8601 (after require "time") prints RFC 3339, e.g. Time.at(ts).utc.iso8601.
  • Time#utc converts the receiver in place; use getutc when the original local Time must stay unchanged.

Random Unix Timestamp Code Examples in Go

Generate random Unix timestamps in Go using time.Now() and math/rand. Covers current time, past/future timestamps, and formatting for testing.

package main

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

// Generate current Unix timestamp (seconds)
func currentTimestamp() int64 {
    return time.Now().Unix()
}

// Generate current Unix timestamp (milliseconds)
func currentTimestampMillis() int64 {
    return time.Now().UnixMilli()
}

// Generate random timestamp between two dates
func randomTimestamp(startDate, endDate string) (int64, error) {
    layout := "2006-01-02"
    start, err := time.Parse(layout, startDate)
    if err != nil {
        return 0, err
    }
    end, err := time.Parse(layout, endDate)
    if err != nil {
        return 0, err
    }

    delta := end.Unix() - start.Unix() + 86400 // through 23:59:59 of the end date
    return start.Unix() + rand.Int63n(delta), nil
}

// Generate random past timestamp (within N days)
func randomPastTimestamp(daysAgo int) int64 {
    now := time.Now().Unix()
    seconds := int64(daysAgo * 86400)
    return now - rand.Int63n(seconds)
}

// Generate random future timestamp (within N days)
func randomFutureTimestamp(daysAhead int) int64 {
    now := time.Now().Unix()
    seconds := int64(daysAhead * 86400)
    return now + rand.Int63n(seconds)
}

// Convert timestamp to readable format
func formatTimestamp(timestamp int64) string {
    return time.Unix(timestamp, 0).Format("2006-01-02 15:04:05")
}

// Generate multiple random timestamps
func generateTimestamps(count int, startDate, endDate string) []int64 {
    timestamps := make([]int64, count)
    for i := 0; i < count; i++ {
        ts, _ := randomTimestamp(startDate, endDate)
        timestamps[i] = ts
    }
    return timestamps
}

func main() {
    fmt.Println("Current:", currentTimestamp())

    random, _ := randomTimestamp("2023-01-01", "2024-12-31")
    fmt.Println("Random:", random)

    past := randomPastTimestamp(30)
    fmt.Printf("Past: %d (%s)\n", past, formatTimestamp(past))

    future := randomFutureTimestamp(30)
    fmt.Printf("Future: %d (%s)\n", future, formatTimestamp(future))

    fmt.Print("Batch: ")
    batch := generateTimestamps(3, "2023-01-01", "2024-12-31")
    for i, ts := range batch {
        fmt.Print(ts)
        if i < len(batch)-1 {
            fmt.Print(", ")
        }
    }
    fmt.Println()
}

How it works in Go

Go time.Now().Unix() returns current Unix timestamp in seconds. time.Parse() parses date strings using Go layout format ("2006-01-02" is reference date). rand.Int63n() generates 64-bit random integers. time.Unix() converts timestamp to Time. Format() uses reference date for formatting. time.Parse() without a zone returns UTC, but time.Now() and time.Unix() return local time: call .UTC() before Format() for UTC output.

Sample output

Current: 1703001234
Random: 1698765432
Past: 1700445678 (2023-11-19 14:27:58)
Future: 1706123456 (2024-01-24 18:10:56)
Batch: 1680123456, 1685432100, 1692345678

Go notes

  • time.Unix(sec, 0) and time.UnixMilli(ms) (Go 1.17+) return local time; chain .UTC().Format(time.RFC3339) for a UTC string.
  • rand.Int63n(n) excludes n and panics when n <= 0, so guard an empty range; math/rand/v2 (Go 1.22) names it rand.Int64N.
  • time.Since(t) and t.Sub(u) use the monotonic clock reading when both times have one, so elapsed times stay correct if the wall clock is adjusted.

Try the Interactive Generator

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

OPEN THE TIMESTAMPS GENERATOR →