Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/timestamps/csharp$ _

Generate Random Timestamps in C#

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: C#

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

Try it: Use our interactive Timestamps generator or integrate this code into your C# application.

Generate random Unix timestamps in C# using DateTimeOffset and Random. Covers current time, past/future timestamps, and formatting 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 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).ToUnixTimeSeconds();
        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))}");
    }
}

[EXPLANATION]

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.

Expected 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

Common Use Cases

  • Generate timestamps for ASP.NET Core Entity Framework testing
  • Create event timestamps for .NET scheduler testing
  • Generate audit timestamps for enterprise applications
  • Test timestamp-based authorization in web APIs
  • Create expiration timestamps for token validation

Important Notes

  • DateTimeOffset is preferred over DateTime for timestamps
  • ToUnixTimeSeconds() available in .NET Core 2.1+
  • UtcNow ensures consistent UTC timestamps
  • TimeSpan.FromDays() is cleaner: TimeSpan.FromDays(30).TotalSeconds
  • Use DateTimeOffset.UtcNow not DateTime.UtcNow for offset awareness

Try Our Interactive Generator

Don't want to write code? Use our free web-based Timestamps generator with instant results.

TRY TIMESTAMPS GENERATOR →