UUID Version 7 Time Ordered
Build RFC 9562 version-7 UUIDs from a 48-bit millisecond timestamp so lexicographic order matches creation time, then verify compareTo follows the clock.
Code
import java.security.SecureRandom;
import java.util.UUID;
public class TimeOrderedIds {
static final SecureRandom RANDOM = new SecureRandom();
// 手工构造 UUIDv7(RFC 9562):48 位 unix 毫秒时间戳占据最高位,
// 字典序 = 时间序;version 位写 0111,variant 位写 10
static UUID generate(long unixMillis) {
long mostSig = (unixMillis << 16) // 48-bit unix millis prefix
| 0x7000L // version 7
| RANDOM.nextInt(1 << 12); // rand_a, 12 bits
long leastSig = (0x2L << 62) // variant 10
| (RANDOM.nextLong() >>> 2); // rand_b, 62 bits
return new UUID(mostSig, leastSig);
}
public static void main(String[] args) {
long base = System.currentTimeMillis();
UUID first = generate(base);
UUID second = generate(base + 1);
UUID third = generate(base + 2);
System.out.println("version of first: " + first.version());
System.out.println("variant of first: " + first.variant());
// 时间上的先后与 compareTo 的字典序完全一致
System.out.println("time order = lex order: "
+ (first.compareTo(second) < 0 && second.compareTo(third) < 0));
UUID older = generate(base - 10);
System.out.println("older sorts before newer: " + (older.compareTo(first) < 0));
}
}The layout of the snippet
One way to read it: the class TimeOrderedIds and the functions generate and main, doing all the work.
Applying it
The entry-point signature is static UUID generate(long unixMillis)
The run emits 4 labeled sections — version of first:, variant of first:, time order = lex order:, older sorts before newer: — one per step.
The entry point wires generate together — run it once and the whole demo flows.
Statements that matter
return new UUID(mostSig, leastSig);
Interactive Tools for This Topic
UUID Version DetectorValidate the 8-4-4-4-12 UUID layout and read its version (v1 to v8) and variant nibbles per RFC 9562, with full field decomposition.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
FAQ
- What does UUID Version 7 Time Ordered print when run?
- Run it as a complete program — the output lines carry labels such as `version of first:`, `variant of first:`, `time order = lex order:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.