Generate Random Timestamps in Java
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Java
What: Generate random Unix timestamps in Java using System.currentTimeMillis() and Random. Covers current time, past/future timestamps, and formatting for testing.
Try it: Use our interactive Timestamps generator or integrate this code into your Java application.
Generate random Unix timestamps in Java using System.currentTimeMillis() and Random. Covers current time, past/future timestamps, and formatting for testing. Looking for other languages? Check our code examples in PHP , JavaScript , Python , C# , C++ , Ruby and Go or use our interactive web generator.
Java Code Example
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"));
}
}
[EXPLANATION]
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.
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 Spring Boot JPA entity testing
- Create event timestamps for Java scheduler testing
- Generate audit log timestamps for enterprise applications
- Test timestamp-based caching in microservices
- Create expiration timestamps for JWT token testing
Important Notes
-
Instantrepresents a point in time (always UTC) -
ThreadLocalRandomis preferred overRandomfor concurrency -
System.currentTimeMillis()returns milliseconds, divide by 1000 for seconds -
ZoneId.systemDefault()uses JVM timezone, useZoneId.of("UTC")for UTC -
Duration.ofDays()is cleaner than manual 86400 calculations
Try Our Interactive Generator
Don't want to write code? Use our free web-based Timestamps generator with instant results.
TRY TIMESTAMPS GENERATOR →Other Programming Languages
View Timestamps generation code examples in PHP
View Timestamps generation code examples in JavaScript
View Timestamps generation code examples in Python
View Timestamps generation code examples in C#
View Timestamps generation code examples in C++
View Timestamps generation code examples in Ruby
View Timestamps generation code examples in Go