java-生成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 }

轉自同事的方法;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM