生成ID模板:年月日时分秒+6位自增码
2015-07-08 16:55
253 查看
由于生成订单ID、商品ID 或者什么什么ID的,不想用自增,又怕重复,于是就用 年与日时分秒 + 6位自增码 (共计20位长度)来当作ID
注意:如果你的ID是Long型,就要注意,Long的最大长度为19位,如果直接转的话会有问题,建议改为年月日时分秒+5位随机数
具体代码:
private static int sequence = 0;
private static int length = 6;
/**
* YYYYMMDDHHMMSS+6位自增长码(20位)
* @author shijing
* 2015年6月29日下午1:25:23
* @return
*/
public static synchronized String getLocalTrmSeqNum() {
sequence = sequence >= 999999 ? 1 : sequence + 1;
String datetime = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
String s = Integer.toString(sequence);
return datetime +addLeftZero(s, length);
}
/**
* 左填0
* @author shijing
* 2015年6月29日下午1:24:32
* @param s
* @param length
* @return
*/
public static String addLeftZero(String s, int length) {
// StringBuilder sb=new StringBuilder();
int old = s.length();
if (length > old) {
char[] c = new char[length];
char[] x = s.toCharArray();
if (x.length > length) {
throw new IllegalArgumentException(
"Numeric value is larger than intended length: " + s
+ " LEN " + length);
}
int lim = c.length - x.length;
for (int i = 0; i < lim; i++) {
c[i] = '0';
}
System.arraycopy(x, 0, c, lim, x.length);
return new String(c);
}
return s.substring(0, length);
}
下面是测试的结果:
2015070816503700001
注意:如果你的ID是Long型,就要注意,Long的最大长度为19位,如果直接转的话会有问题,建议改为年月日时分秒+5位随机数
具体代码:
private static int sequence = 0;
private static int length = 6;
/**
* YYYYMMDDHHMMSS+6位自增长码(20位)
* @author shijing
* 2015年6月29日下午1:25:23
* @return
*/
public static synchronized String getLocalTrmSeqNum() {
sequence = sequence >= 999999 ? 1 : sequence + 1;
String datetime = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
String s = Integer.toString(sequence);
return datetime +addLeftZero(s, length);
}
/**
* 左填0
* @author shijing
* 2015年6月29日下午1:24:32
* @param s
* @param length
* @return
*/
public static String addLeftZero(String s, int length) {
// StringBuilder sb=new StringBuilder();
int old = s.length();
if (length > old) {
char[] c = new char[length];
char[] x = s.toCharArray();
if (x.length > length) {
throw new IllegalArgumentException(
"Numeric value is larger than intended length: " + s
+ " LEN " + length);
}
int lim = c.length - x.length;
for (int i = 0; i < lim; i++) {
c[i] = '0';
}
System.arraycopy(x, 0, c, lim, x.length);
return new String(c);
}
return s.substring(0, length);
}
下面是测试的结果:
2015070816503700001
相关文章推荐
- vim模式介绍
- 最全的正则表达式
- 主流服务器apache、IIS、tomcat、jboss、resin、weblogic、websphere的区别
- 特征处理(Feature Processing)
- 人类家族类(类继承与接口实现)===API
- memcached全面剖析–2.理解memcached的内存存储
- Dokcer学习笔记之Dokcerfile 文件构建
- 使用简单的html+css+javacsript实现dialog功能
- 环境互换
- Java中的值传递和引用传递
- ImageView.ScaleType设置图解
- 禁止键盘输入表情
- git入门三
- 17.合并两个排序的链表
- u-boot 4、u-boot.lds
- iOS UIButton在某些情况下不能立刻响应TouchDown事件
- 手机家族类(接口实现)
- js数组的定义方法与基本使用
- 《译文》借助OCR和神经网络,用JavaScript识别验证码
- $_SERVER