java - 如何使用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
解决方案
您想要的格式化程序"yyyy-M-d"
将同时处理一位数和两位数month
和day
值:
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
解析String
为LocalDate
.
推荐阅读
- c++ - 为什么从 .txt 文件中提取的文本最后包含一个空格字符以及如何删除它?
- python-3.x - Tika OCR 在 Windows Server 上运行时会随着时间的推移而变慢
- html - 如何覆盖 CSS 文件的链接 scss
- angular - 未涵盖声纳覆盖角度单元测试
- angular - 页面加载角度
- oracle - 使用 Oracle dbms_json 解析 json 数组的字符串
- multithreading - 多进程的进程间通信
- asp.net-core - 在 IIS 上的 ASP.NET Core 中为 Windows 身份验证配置 Kerberos
- git - 我不确定我的本地存储库是否处于正确的状态以推送到我的远程
- angular - 未拾取 ActivatedRoute 参数