根据时间生成流水号

第一种

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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));
}
}

第二种

1
2
3
4
5
6
7
8
9
10
11
12
13
//获得当前时间戳
DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime localDateTime = LocalDateTime.now();
//时间戳转换格式
String newDate = sdf.format(localDateTime);
//时间戳加三位随机数,根据并发量定
Random random = new Random();
for (int i = 0; i < 3; i++) {
newDate += random.nextInt(10);
}
//输出订单号
System.out.println(newDate);

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

扫一扫,分享到微信

微信分享二维码

请我喝杯咖啡吧~

支付宝
微信