【Java】生成一个随机生日

【需求】

将身份证中的原有生日部分以一个随机生日替换掉,需要动态生成随机生日。

【代码】

package com.hy.lab;

public class RndBirthday {
    // 取得min和max之间包括端点的随机整数
    private static int rnd(int min,int max) {
        return (int)(min+Math.random()*(max-min+1));
    }

    // 取得一个随机日期,使用占位符合保证8位
    private static String generateBirthday(){
        int y=rnd(1970,2022);
        int m=rnd(1,12);
        int d=rnd(1,28);

        return String.format("%04d%02d%02d",y,m,d);// 02d 用0补缺 2d 用空格补缺
    }

    // 测试
    public static void main(String[] args){
        for(int i=0;i<10;i++){
            System.out.println(generateBirthday());
        }
    }
}

【输出】

19860705
20060105
19790801
20130519
19810311
20030523
19820713
20210727
19881024
20030911

END

 

posted @ 2022-05-29 09:04  逆火狂飙  阅读(870)  评论(0)    收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东