I need to create a unique ID or reference number that's based on the current time format yymmddHHmmss + (sequence 0-9). I know about UUID but I prefer this instead. Can someone show me how to do it in Java? Thanks.
Unique ID based on Current Date Format yymmddHHmmss in Java
1.3k Views Asked by Master EZ At
2
There are 2 best solutions below
0
On
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. Here’s a suggestion doing so.
private static final int MIN_SEQ = 0;
private static final int MAX_SEQ = 9;
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("yyMMddHHmmss");
private LocalDateTime lastTime = LocalDateTime.now(ZoneId.systemDefault())
.minusMinutes(1); // Initialize to a time in the past
private int lastSeq = 0; // Initialize to any value
public String getUniqueId() {
LocalDateTime time = LocalDateTime.now(ZoneId.systemDefault())
.truncatedTo(ChronoUnit.SECONDS);
if (time.isBefore(lastTime)) {
throw new IllegalStateException("Time is going backward");
}
if (time.isAfter(lastTime)) {
lastTime = time;
lastSeq = MIN_SEQ;
} else { // Still the same time
lastSeq++;
}
if (lastSeq > MAX_SEQ) {
throw new IllegalStateException("Out of sequence numbers for this time");
}
return lastTime.format(FORMATTER) + lastSeq;
}
It will break miserably under the following two circumstances:
- If used during the spring back where clocks are turned back and the same times repeat.
- If the time zone of your JVM is changed. Any part of your program and any other program running in the same JVM may do that at any time.
It will also give non-increasing IDs if the program happens to be running by New Year 2100. Since a LocalDateTime includes full year, it will continue running and giving IDs, though.
Why not try it out?
for (int i = 0; i < 12; i++) {
System.out.println(getUniqueId());
TimeUnit.MILLISECONDS.sleep(150);
}
In one case output was:
2104212202180 2104212202181 2104212202190 2104212202191 2104212202192 2104212202193 2104212202194 2104212202195 2104212202196 2104212202200 2104212202201 2104212202202
Link
Oracle tutorial: Date Time explaining how to use java.time.
Use simple date formatter to format the current timestamp to 'yymmddHHmmss' and use a global variable to get the sequence number for that timestamp.
Output