java按天生成两位流水号

2023-12-22 05:45:51

直接利用redis的incrBy即可。

    private String getNewTaskNo() {
        String today = DateTimeUtil.dateToStr(new Date(), "yyyyMMdd");
        Long newNo = redisUtil.incrBy(today, 1);
        redisUtil.expire(today, 3600 * 24);
        return today + "-" + newNo;
    }

如果要精确控制expire的time,则可以使用

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 24);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        int lockTime = (int) ((calendar.getTimeInMillis() - System.currentTimeMillis()) / 1000);

如果要前面填充一个0,则:

    private String getNewTaskNo() {
        String today = DateTimeUtil.dateToStr(new Date(), "yyyyMMdd");
        Long newNo = redisUtil.incrBy(today, 1);
        redisUtil.expire(today, 3600 * 24);
        if (newNo < 10) {
            return today + "-" + "0" + newNo;
        }
        return today + "-" + newNo;
    }

文章来源:https://blog.csdn.net/qq_35890572/article/details/135103863
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。