JAVA 用时间生成主键ID

作者: gavin 分类: Java,Java 基础 发布时间: 2022-02-14 13:30
/** 
*   生成主键(19位数字)
*  主键生成方式,年月日时分秒毫秒的时间戳 例如:1810311557430000845
*/ 
    public static synchronized Long getUUIDTOLongNew(){
        try {
            TimeUnit.NANOSECONDS.sleep(1000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String msg=""; 
        Date date = new Date(); 
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSSSSSS"); //1810311557430000845
//        msg = sdf.format(date).substring(2); 
        return Long.parseLong(sdf.format(date));
    }

 /** 
  *   生成主键(17位数字)
  *  主键生成方式,年月日时分秒毫秒的时间戳 例如:180910094204299
    */ 
public static synchronized Long getUUIDTOLong(){
   try {
      Thread.sleep(1);
   } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
   String msg=""; 
   Date date = new Date(); 
   SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); 
   msg = sdf.format(date).substring(2); 
   return Long.parseLong(msg);
}

UUID生成主键

UUID uuid = UUID.randomUUID();
String id = uuid.toString().replace("-", "").toLowerCase();

//toLowerCase() 将字符串转换为小写