在日常开发中,经常会遇到根据年月日和第几号文件生成对应的编号,今天给大家提供一个简单的工具类
public static final Long CODE=1L;
    /**
     * @param select 数据库中数据总数
     * @return
     */
    public static String SubjectNo(Long select){
        // 在总数的基础上+1,用来标识新增数据的编号
        String code = sequenceCode(1000, select+CODE);
        Date date=new Date();
        SimpleDateFormat sf=new SimpleDateFormat("yyyy");  // 获取年份
        SimpleDateFormat sf1=new SimpleDateFormat("MM");   // 获取月份
        SimpleDateFormat sf2=new SimpleDateFormat("dd");   // 获取日期
        String year = sf.format(date);    // 取出年
        String month = sf1.format(date);  // 取出月份
        String day = sf2.format(date);    // 取出日期
        return year+month+day+"-"+code;
    } 
sequenceCode方法的代码如下
/**
     * 生成001的编号
     * @param maxNum 最大数
     * @param count  累计的
     * @return
     */
    public static String sequenceCode(Integer maxNum, Long count) {  // 如生成001这种,maxNum为1000  0001的话maxNum则为10000,count则是我们从数据库中查询的总数
        String strNum = String.valueOf(maxNum + count);
        if (StringUtils.isEmpty(strNum) || 1 == strNum.length()) {
            return "";
        }
        return strNum.substring(1);
    } 
测试一下吧

该示例 测试为年月日+序号递增,如果该业务要求实现按年份+序号递增 只需改一下图一代码即可



















