根據時間生成流水號
阿新 • • 發佈:2019-01-25
package test; import java.text.SimpleDateFormat; import java.util.Date; /** * 獲取主鍵:返回17位時間戳+3位遞增數(同一時間遞增) */ public class IdCreator { private static int addPart = 1; private static String result = ""; private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); private static String lastDate = ""; /** * 獲取主鍵 * @param length 長度 * @return 返回17位時間戳+3位遞增數 */ public synchronized static String getId(int length) { //獲取時間部分字串 Date now = new Date(); String nowStr = sdf.format(now); //獲取數字字尾值部分 if (IdCreator.lastDate.equals(nowStr)) { addPart += 1; } else { addPart = 1; lastDate = nowStr; } if (length > 17) { length -= 17; for (int i = 0; i < length - ((addPart + "").length()); i++) { nowStr += "0"; } nowStr += addPart; result = nowStr; } else { result = nowStr; } return result; } public static void main(String[] args) { System.out.println(IdCreator.getId(20)); } }