package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class test01 {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
// TODO 自動生成されたメソッド・スタブ
Date dbDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dbDate = (Date) dateFormat.parse("1990-05-08");
System.out.println(getAge(dbDate));
}
public static int getAge(Date dateOfBirth) {
int age = 0;
Calendar born = Calendar.getInstance();
Calendar now = Calendar.getInstance();
if (dateOfBirth != null) {
now.setTime(new Date());
born.setTime(dateOfBirth);
if (born.after(now)) {
throw new IllegalArgumentException(
"Can't be born in the future");
}
age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
age -= 1;
}
}
return age;
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class test01 {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
// TODO 自動生成されたメソッド・スタブ
Date dbDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dbDate = (Date) dateFormat.parse("1990-05-08");
System.out.println(getAge(dbDate));
}
public static int getAge(Date dateOfBirth) {
int age = 0;
Calendar born = Calendar.getInstance();
Calendar now = Calendar.getInstance();
if (dateOfBirth != null) {
now.setTime(new Date());
born.setTime(dateOfBirth);
if (born.after(now)) {
throw new IllegalArgumentException(
"Can't be born in the future");
}
age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
age -= 1;
}
}
return age;
}
}
本文介绍了一个使用Java实现的程序,该程序能够解析日期字符串并计算出生年份对应的当前年龄。程序中涉及了日期格式化、解析、年龄计算等核心功能,通过实例演示了如何在Java中进行日期操作。
4833

被折叠的 条评论
为什么被折叠?



