如何使用 java 在 int 字段的左侧添加零
How to add zero on the left on a int field using java
我正在尝试将个人号码与当前日期进行比较以获取此人的年龄。
目前的问题是,如果我的个人号码中有一个零,它就会被删除,所以我无法解析它。
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);
}
这是我遇到的错误
线程 "main" 中出现异常 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 docs:
Number: If the count of letters is one, then the value is output using
the minimum number of digits and without padding. Otherwise, the count
of digits is used as the width of the output field, with the value
zero-padded as necessary.
如果您是 Java 8+,请不要使用 SimpleDateFormat
类。我假设你在 Java 8 上使用 LocalDate
类。此外,不要使用带有硬编码索引的 String#substring
来分隔日期组件,而是使用 DateTimeFormatter#ofPattern
将 String
日期解析为 LocalDate
.
你可能不需要这两行:
int month = Integer.parseInt(temp.substring(2, 4));
int day = Integer.parseInt(temp.substring(0, 2));
因为您再次将这些整数添加到字符串中。
StringBuilder birthday = new StringBuilder();
birthday.append(year);
birthday.append("-");
birthday.append(temp.substring(2,4));
birthday.append("-");
birthday.append(temp.substring(0,2));
LocalDate date1 = LocalDate.parse(birthday.toString());
试试这个:
// Pass the date in YYYY-MM-dd format, i.e., 1995-1-15
@SuppressLint("SimpleDateFormat")
public void parseDate(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
try {
// Parsing and then formatting date using SimpleDateFormat object.
String requiredDate = dateFormat.format(dateFormat.parse(date));
// Printing in the log
Log.d("Parsed Date", requiredDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
我假设丹麦语 personnumer(人号,“社会安全号码”)格式为
ddmmyycxxg
例如,对于 2001 年 8 月 24 日出生的女性,数字可能是
2408018314
数字表示:
dd
: 生日
mm
出生月份
yy
出生年份
c
出生世纪代码;由于历史原因,它的意思是:
- 0–3: 1900–1999
- 4 或 9:1937–2036
- 5–8 1858–1899 或 2000–2057
xx
任意数字
g
性别代码:女性偶数,男性奇数
或者在代码中:
DateTimeFormatter formatter1858 = formatterWithBaseYear(1858);
DateTimeFormatter formatter1900 = formatterWithBaseYear(1900);
DateTimeFormatter formatter1937 = formatterWithBaseYear(1937);
DateTimeFormatter formatter2000 = formatterWithBaseYear(2000);
String personnummer = "2408018314";
char centuryCode = personnummer.charAt(6);
String birthDateString = personnummer.substring(0, 6);
LocalDate dateOfBirth;
switch (centuryCode) {
case '0':
case '1':
case '2':
case '3':
// 1900 - 1999
dateOfBirth = LocalDate.parse(birthDateString, formatter1900);
break;
case '4':
case '9':
// 1937 - 2036
dateOfBirth = LocalDate.parse(birthDateString, formatter1937);
break;
case '5':
case '6':
case '7':
case '8':
// 1858 - 1899 or 2000 - 2057
dateOfBirth = LocalDate.parse(birthDateString, formatter1858);
if (dateOfBirth.getYear() > 1899) {
dateOfBirth = LocalDate.parse(birthDateString, formatter2000);
assert dateOfBirth.getYear() >= 2000 && dateOfBirth.getYear() <= 2057 : dateOfBirth;
}
break;
default:
throw new IllegalStateException("Not a valid digit: " + centuryCode);
}
LocalDate today = LocalDate.now(ZoneId.of("Europe/Copenhagen"));
if (dateOfBirth.isAfter(today)) {
System.out.println("This person was born in the future??");
}
long ageInYears = ChronoUnit.YEARS.between(dateOfBirth, today);
System.out.println(ageInYears);
我正在使用以下辅助方法来构建四个格式化程序:
private static DateTimeFormatter formatterWithBaseYear(int year) {
return new DateTimeFormatterBuilder()
.appendPattern("ddMM")
.appendValueReduced(ChronoField.YEAR, 2, 2, year)
.toFormatter();
}
片段打印:
18
我发现您的代码存在以下问题:
- 似乎没有考虑到一个人可能超过100岁。似乎假设出生年份是从1920年到2019年。如果你在4个月后的新生婴儿身上尝试它也会造成麻烦(出生年份将是2020年)。
- 你试图使用众所周知的麻烦和过时的
SimpleDateFormat
和同样过时的 Date
class.
- 您正在分别解析日、月和年。最好将整个解析留给一个
DateTimeFormatter
。它将立即解析所有内容,并提供我们获得有效日期的验证。
- 将已解析的数字转换回新字符串并再次解析该字符串会使事情变得过于复杂(这也是您在解析一位数字时遇到麻烦的原因)。避免所有这些。
- 要获取今天的日期,只需使用
LocalDate.now(yourTimeZone)
。没有理由进行任何格式化或解析。
Link: Personnummeret i CPR-systemet(中央人员登记系统中的人员编号)记录数字的含义(丹麦语)。
我正在尝试将个人号码与当前日期进行比较以获取此人的年龄。
目前的问题是,如果我的个人号码中有一个零,它就会被删除,所以我无法解析它。
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);
}
这是我遇到的错误
线程 "main" 中出现异常 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 docs:
Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary.
如果您是 Java 8+,请不要使用 SimpleDateFormat
类。我假设你在 Java 8 上使用 LocalDate
类。此外,不要使用带有硬编码索引的 String#substring
来分隔日期组件,而是使用 DateTimeFormatter#ofPattern
将 String
日期解析为 LocalDate
.
你可能不需要这两行:
int month = Integer.parseInt(temp.substring(2, 4));
int day = Integer.parseInt(temp.substring(0, 2));
因为您再次将这些整数添加到字符串中。
StringBuilder birthday = new StringBuilder();
birthday.append(year);
birthday.append("-");
birthday.append(temp.substring(2,4));
birthday.append("-");
birthday.append(temp.substring(0,2));
LocalDate date1 = LocalDate.parse(birthday.toString());
试试这个:
// Pass the date in YYYY-MM-dd format, i.e., 1995-1-15
@SuppressLint("SimpleDateFormat")
public void parseDate(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
try {
// Parsing and then formatting date using SimpleDateFormat object.
String requiredDate = dateFormat.format(dateFormat.parse(date));
// Printing in the log
Log.d("Parsed Date", requiredDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
我假设丹麦语 personnumer(人号,“社会安全号码”)格式为
ddmmyycxxg
例如,对于 2001 年 8 月 24 日出生的女性,数字可能是
2408018314
数字表示:
dd
: 生日mm
出生月份yy
出生年份c
出生世纪代码;由于历史原因,它的意思是:- 0–3: 1900–1999
- 4 或 9:1937–2036
- 5–8 1858–1899 或 2000–2057
xx
任意数字g
性别代码:女性偶数,男性奇数
或者在代码中:
DateTimeFormatter formatter1858 = formatterWithBaseYear(1858);
DateTimeFormatter formatter1900 = formatterWithBaseYear(1900);
DateTimeFormatter formatter1937 = formatterWithBaseYear(1937);
DateTimeFormatter formatter2000 = formatterWithBaseYear(2000);
String personnummer = "2408018314";
char centuryCode = personnummer.charAt(6);
String birthDateString = personnummer.substring(0, 6);
LocalDate dateOfBirth;
switch (centuryCode) {
case '0':
case '1':
case '2':
case '3':
// 1900 - 1999
dateOfBirth = LocalDate.parse(birthDateString, formatter1900);
break;
case '4':
case '9':
// 1937 - 2036
dateOfBirth = LocalDate.parse(birthDateString, formatter1937);
break;
case '5':
case '6':
case '7':
case '8':
// 1858 - 1899 or 2000 - 2057
dateOfBirth = LocalDate.parse(birthDateString, formatter1858);
if (dateOfBirth.getYear() > 1899) {
dateOfBirth = LocalDate.parse(birthDateString, formatter2000);
assert dateOfBirth.getYear() >= 2000 && dateOfBirth.getYear() <= 2057 : dateOfBirth;
}
break;
default:
throw new IllegalStateException("Not a valid digit: " + centuryCode);
}
LocalDate today = LocalDate.now(ZoneId.of("Europe/Copenhagen"));
if (dateOfBirth.isAfter(today)) {
System.out.println("This person was born in the future??");
}
long ageInYears = ChronoUnit.YEARS.between(dateOfBirth, today);
System.out.println(ageInYears);
我正在使用以下辅助方法来构建四个格式化程序:
private static DateTimeFormatter formatterWithBaseYear(int year) {
return new DateTimeFormatterBuilder()
.appendPattern("ddMM")
.appendValueReduced(ChronoField.YEAR, 2, 2, year)
.toFormatter();
}
片段打印:
18
我发现您的代码存在以下问题:
- 似乎没有考虑到一个人可能超过100岁。似乎假设出生年份是从1920年到2019年。如果你在4个月后的新生婴儿身上尝试它也会造成麻烦(出生年份将是2020年)。
- 你试图使用众所周知的麻烦和过时的
SimpleDateFormat
和同样过时的Date
class. - 您正在分别解析日、月和年。最好将整个解析留给一个
DateTimeFormatter
。它将立即解析所有内容,并提供我们获得有效日期的验证。 - 将已解析的数字转换回新字符串并再次解析该字符串会使事情变得过于复杂(这也是您在解析一位数字时遇到麻烦的原因)。避免所有这些。
- 要获取今天的日期,只需使用
LocalDate.now(yourTimeZone)
。没有理由进行任何格式化或解析。
Link: Personnummeret i CPR-systemet(中央人员登记系统中的人员编号)记录数字的含义(丹麦语)。