基础(二)之创建每天重置的流水号和计算时间差

本文介绍了两种创建每天重置的流水号的方法,包括基于时间生成和利用Redis原子自增特性,并提供了相应的代码实现。同时,文章详细阐述了如何计算时间差,分别展示了使用SimpleDateFormat和Joda时间库进行计算的示例及运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种方式:

 首先,根据时间生成,我们先要格式化一下时间格式

SimpleDateFormat dmfot = new SimpleDateFormat("yyyyMMdd");
//截取当前时间作为流水号
String preCode = dmfot.format(new Date());

 然后我们进行数据库查询,今天最大的流水号是多少? 

//获取最大编号
String maxCode = getMaxCode(date);
查询语句如下:
select Max(code)
from table_name
where 
declare_time >= STR_TO_DATE(#{date},'%Y-%m-%d')

 这里我们重置一下时间格式,获取当前时间零点

  /**
	 * 返回当前时间零点
	 * @return
	 */
	public static String getCurrentDay() {
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Calendar c = Calendar.getInstance();
	    c.setTime(new Date()); 
    	    c.set(Calendar.HOUR_OF_DAY, 0);  
    	    c.set(Calendar.MINUTE, 0);  
    	    c.set(Calendar.SECOND, 0);
    	    Date date = c.getTime();
    	    String currentDay = format.format(date);
		return currentDay;
	}

 查询之后进行判断,如果查出的数据为空,证明今天没有生成流水号,我们直接set

//设置流水号格式,根据实际情况设置
DecimalFormat num=new DecimalFormat("000");
if(maxCode != null && !"null".equals(maxCode)){
        //对流水号截取后三位
	String code = maxCode.substring(maxCode.length()-3,maxCode.length());
        //例如后三位为002,通过以下步骤,将会变为003
	int count = Integer.valueOf(code)+1;
	String number = num.format(count);
	return preCode + "-" + number;
}else {
    return preCode + "-" + "001";
}

"001";例如  20191017-001

第二种: 

1、使用redis原子自增特性

  2、先判断key,是否存在

    2.1、存在:顺序码自增

    2.2、不存子:重新生成顺序码

代码实现

控制器

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestContr
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值