java-生成id的方法(时间+随机数)

本文介绍了一种基于当前时间和随机数生成唯一ID的方法。通过使用特定的时间格式和固定长度的随机数相结合,确保了ID的唯一性和高效性。
 1 package com.dawning.gridview.app.infrastructure.webapp.devicecontrol.global;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 
 6 /**
 7  * 生成id
 8  * @author wjy
 9  *
10  */
11 public class GeneratID {
12     /**
13     * 根据传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。
14     *
15     * @param sformat
16     *            yyyyMMddhhmmss
17     * @return
18     */
19     public static String getDate(String sformat) {
20        Date currentTime = new Date();
21        SimpleDateFormat formatter = new SimpleDateFormat(sformat);
22        String dateString = formatter.format(currentTime);
23        return dateString;
24     }
25 
26     public static String getRandomNum(int num){
27         String numStr = "";
28         for(int i = 0; i < num; i++){
29             numStr += (int)(10*(Math.random()));
30         }
31         return numStr;
32     }
33     /**
34      * 生成id
35      * @return
36      */
37     public static Long getGeneratID(){
38         String sformat = "MMddhhmmssSSS";
39         int num = 3;
40         String idStr = getDate(sformat) + getRandomNum(num);
41         Long id = Long.valueOf(idStr);
42         return id;
43     }
44 
45     public static void main(String[] args) {
46         for(int i = 0; i < 1; i++){
47             System.out.println(getGeneratID());
48         }
49     }
50 }

转自同事的方法;

转载于:https://www.cnblogs.com/My-Cloud/p/4546317.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值