商品批次號解析工具類


背景:商品的批次號規則為恆定為八位日期數字“yyyyMMdd”,如“20200520”,代表着該商品是2020年05月20日生產的,該商品的效期是恆定的,單位為月

需求:批次號輸入的時候校驗格式,通過批次號和效期得到生產日期和失效日期

方法:

   一、建立批號工具類(BatchNumberUtil)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @ClassName BatchNumberUtil
 * @Description 批次號工具
 * @Author 北海派
 * @Date 2020/5/20 12:25
 * @Version 1.0
 **/
public class BatchNumberUtil {

    private static final Logger log = LoggerFactory.getLogger("BatchNumberUtil.class");

    /**
     * 校驗格式
     *
     * @param batchNumber 20200508
     * @return
     */
    public static boolean isValidDate(String batchNumber) {
        boolean result = true;
        if (!StringUtils.isEmpty(batchNumber)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            try {
                format.setLenient(false);
                format.parse(batchNumber);
            } catch (ParseException e) {
                result = false;
                log.error("批次號格式異常:{}", batchNumber);
            }
        } else {
            result = false;
        }
        return result;
    }

    /**
     * 獲取生產日期和失效日期
     *
     * @param batchNumber 批次號
     * @param month       效期(月數)
     * @return
     */
    public static List<Date> getDates(String batchNumber, Integer month) {

        List<Date> dateList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Date production = null;
        Date invalid;
        if (!StringUtils.isEmpty(batchNumber) && month != null && month > 0) {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            try {
                format.setLenient(false);
                production = format.parse(batchNumber);
            } catch (ParseException e) {
                log.error("批次號格式異常:{}", batchNumber);
            }
            if (null != production) {
                calendar.setTime(production);
                calendar.add(Calendar.MONTH, month);
                invalid = calendar.getTime();

                dateList.add(0, production);
                dateList.add(1, invalid);
            }
        }
        return dateList;

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM