首页 > 解决方案 > 如何使用java在int字段的左侧添加零

问题描述

我正在尝试将个人编号与当前日期进行比较以获取人员年龄。

当前的问题是,如果我的个人号码中有一个零,它会被删除,所以我无法解析它。

        for (int i = 0; i <= personList.size(); i++) {

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String date = formatter.format(new Date());

            String temp = personList.get(i).getCPR();
            int year = Integer.parseInt((temp.substring(4, 6)));
            if (year < 20) {
                year += 2000;
            } else {
                year += 1900;
            }

            int month = Integer.parseInt(temp.substring(2, 4));
            int day = Integer.parseInt(temp.substring(0, 2));

            /*if (month if month don't start with zero){
                    add 0 to month on the left
                }
                    same goes for day*/


            String birthday = year + "-" + month + "-" + day;

            LocalDate date1 = LocalDate.parse(birthday);
            LocalDate date2 = LocalDate.parse(date);

            long age = date1.until(date2, ChronoUnit.YEARS);

            System.out.println(age);
        }

这是我得到的错误

线程“主”java.time.format.DateTimeParseException 中的异常:无法在索引 5 处解析文本“1995-1-13”

我希望 1995-1-13 阅读 1995-01-13

标签: javaparsingif-statementintsimpledateformat

解决方案


您想要的格式化程序"yyyy-M-d"将同时处理一位数和两位数monthday值:

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
 String temp ="1995-1-13";

 LocalDate date1 = LocalDate.parse(temp, formatter);
 long age = date1.until(LocalDateTime.now(), ChronoUnit.YEARS);
 System.out.println(age);

输出:

 24

这是根据 JDK文档

数字:如果字母数为 1,则使用最小位数输出值且不进行填充。否则,位数将用作输出字段的宽度,必要时将值补零。

SimpleDateFormat如果您使用的是 Java 8+,请不要使用这些类。我假设您在使用LocalDate类时使用的是 Java 8。此外,不要使用String#substring硬编码索引来分隔日期组件, 而是使用 将日期DateTimeFormatter#ofPattern解析StringLocalDate.


推荐阅读