工具类,生称编号

本文介绍了一个用于按照指定模板生成下一编号的Java方法。该方法能够根据当前编号、模板字符串及指定的时间和编号位置,生成符合规则的新编号。适用于需要按特定格式递增编号的场景。
package util;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetNextNumber {
    /**
     * 
     * describe: 按照模版生成编号
     * user:choiyubo
     * date:2017年6月5日下午7:28:59
     * @param model 起始编号[2016][0000]
     * @param oldno 当前的编号
     * @param yearStart 时间开始下标(下标从0开始)
     * @param noStart 编号开始下标(下标从0开始)
     * @param noLength 编号长度
     * @return 新的编号
     */
    public static String getnextnumber(String model,String oldnumber,int yearStart,int noStart,int noLength){
        
        if(oldnumber==null||oldnumber.length()!=model.length()){//如果没有参数,模版的长度和传入的不一致,则返回模版
            oldnumber= model;
        }
        StringBuffer newno=new StringBuffer("");
        SimpleDateFormat df=new SimpleDateFormat("yyyy");
        int year= Integer.valueOf(df.format(new Date()));
        newno.append(oldnumber.substring(0,yearStart));//时间之前
        newno.append(year);//时间
        newno.append(oldnumber.substring(yearStart+4,noStart));//时间之后,no之前
        int no=Integer.valueOf(oldnumber.substring(noStart,noStart+noLength));//原来的no
        String modelno=model.substring(noStart,noStart+noLength);//模版的no
        String newnum=new DecimalFormat(modelno).format(no+1);
        
        if(newnum.length()>noLength){
            newnum=modelno;
        }
        newno.append(newnum);//新的number
        newno.append(oldnumber.substring(noStart+noLength));
        return newno.toString();
    }    
    


}

测试方法如下

package util;


import org.junit.Before;
import org.junit.Test;

public class GetNextNumberTest {
    
    private static GetNextNumber getNextNumber=new GetNextNumber();
    @Before
    public void setUp() throws Exception {
        
    }

    @SuppressWarnings("static-access")
    @Test
    public void test() {
        String model="[2016][00000]";//模版
        String oldnumber=null;//当前的编号
        String testnumber="[2016][00001]";//预期的结果
        int yearStart=1;
        int noStart=7;
        int noLength=5;
        String newnumber=getNextNumber.getnextnumber(model, oldnumber, yearStart, noStart, noLength);
        assert(testnumber.equals(newnumber));
    }

}

 

转载于:https://www.cnblogs.com/choiyubo163com/p/6946798.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值