工作中需要按照需求设置固定的编号,就用到了String.format()这里做一下记录
public static void main(String[] args) {
//A20191209030001
//A固定开头
//20191209时间
//03员工编号
//0001产品编号
String newPlanNo = newPlanNo("A20191209030001","A");
System.out.println(newPlanNo);
}
public static String newPlanNo(String planNo,String ty) {
String newPlanNo ="";
SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
StringBuilder sb = new StringBuilder();
if (planNo == null||planNo.equals("")) {
sb.append(ty)
.append(Long.parseLong(s.format(new Date())))
.append(String.format("%02d",3))
.append(String.format("%04d",1));
newPlanNo = String.format("%19s", sb.toString()).trim();
} else {
String regEx="[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(planNo);
String str = m.replaceAll("").trim();
int length = str.length();
System.out.println(length);
String substring = str.substring(length-4,length);
System.out.println(substring);
sb.append(ty)
.append(Long.parseLong(s.format(new Date())))
.append(String.format("%02d",3))
.append(String.format("%04d",Integer.parseInt(substring)+1));
newPlanNo = String.format("%19s", sb.toString()).trim();
}
return newPlanNo;
}