Monday, 21 December 2015

Create unique ID : use timestamp for it in Java

Whenever we require a unique ID for different purposes. We try with various approach.
One of good approach is to use timestamp with specific format. Please find the code for the same.

getTrackignID function will give you unique ID for the use.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetUniqueID {


         String defaultFormat="yyMMddHHmmss";
         String trackingID=null;

         private final long startTime=System.nanoTime();

private static final long deltaNanos = System.currentTimeMillis() * 1000000L - System.nanoTime();

private DateFormat dateFormat;

public DateFormat getDateFormat() {
return dateFormat;
}

public void setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}

public long getStartTime()
{
return ((this.startTime + deltaNanos) / 1000000L);
}

         public String getTrackignID(){
setDateFormat(new SimpleDateFormat(defaultFormat));
String trackingID=null;
trackingID=getTimestamp();
System.out.println("Generated tracking ID :"+trackingID);
return trackingID;

}

private String getTimestamp() {
return this.dateFormat.format(new Date(getStartTime()));
}
}

output will in format below :

151221123634 as per the format "yyMMddHHmmss"

No comments:

Post a Comment