java 生成单号

 

import java.text.DecimalFormat;

import java.text.Format;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.GregorianCalendar;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

 

import wt.cache.CacheManager;

 

public class NumberProduce {

private static Map<String, String> map = new HashMap<String, String>();

private static String STATNUM = "0";

 

private String getLastSixNum(int seq, int length) {

String formatStr = "";

for(int i=0; i<length; i++){

formatStr+= "0";

}

DecimalFormat numformat = new DecimalFormat(formatStr);

String rs = numformat.format(seq+1);

return rs;

}

 

private static void cleanMap(Map<String, String> map) {

if(map == null){

return ;

}

//当前时间

GregorianCalendar nowDate=new GregorianCalendar(); 

nowDate.setTime(new Date());

nowDate.add(Calendar.DATE, -3);

 

SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");

GregorianCalendar keyDate=new GregorianCalendar(); 

try {

Iterator<String> it = map.keySet().iterator();  

       while(it.hasNext()){  

   String key = it.next();

//集合中的时间时间

String keyDateStr = key.substring(key.indexOf("_")+1);

Date tempKeyDate = dateformat.parse(keyDateStr);

keyDate.setTime(tempKeyDate);

 

System.out.println(key+":"+keyDate.before(nowDate));

if(keyDate.before(nowDate)){

it.remove();

}

}

} catch (ParseException e) {

e.printStackTrace();

System.out.println("清除今天之前的缓存序列数据失败");

}

 

}

 

public synchronized String getNum(String prefix,int length) {

//CacheManager ss = new CacheManager();

Format dateformat = new SimpleDateFormat("yyyyMMdd");

String ymd = dateformat.format(new Date());

String key = prefix+"_"+ymd;

String lastNumStr = map.get(key)==null ?STATNUM:map.get(key);

int lastNum = Integer.parseInt(lastNumStr);

map.put(key, getLastSixNum(lastNum,length));

 

return prefix + ymd + map.get(key);

}

 

public static void main(String[] args) {

NumberProduce t = new NumberProduce();

String prefix = "BOM";

int length = 4;

//System.out.println(t.getNum(prefix,length));

//System.out.println(t.getNum(prefix,length));

//System.out.println(t.getNum(prefix,length));

 

Map<String, String> map1 = new HashMap<String, String>();

map1.put("BOM_20150606", "BOM201506060001");

map1.put("BOM_20150605", "BOM201506060001");

map1.put("BOM_20150604", "BOM201506060001");

map1.put("BOM_20150603", "BOM201506060001");

map1.put("BOM_20150602", "BOM201506060001");

map1.put("BOM_20150601", "BOM201506060001");

cleanMap(map1);

 

System.out.println(map1);

 

}

}

你可能感兴趣的:(java)