java ee 中输入一个人的生日,怎么算出他如今多少岁
发布网友
发布时间:2022-05-11 06:58
我来回答
共3个回答
热心网友
时间:2023-10-06 04:18
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class GetAge {
public static void main(String[] args) throws ParseException {
System.out.println("输入出生年月日如:2015-2-20");
Scanner s = new Scanner(System.in);
String input = s.next();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
Date birthday = sdf.parse(input);
Date nowDate = new Date();
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(nowDate);
c2.setTime(birthday);
int age = c1.get(Calendar.YEAR)- c2.get(Calendar.YEAR);
System.out.println(age);
}
}
热心网友
时间:2023-10-06 04:18
import java.io.*;
import java.util.*;
public class GetBirth {
int year = 0;
int month = 0;
int day = 0;
Calendar cld = Calendar.getInstance();//创建一个日历
public GetBirth(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入年、月、日:");
try {
year = Integer.parseInt(in.readLine());
month = Integer.parseInt(in.readLine());
day = Integer.parseInt(in.readLine());
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//将日历时间设置成生日那天
public void setDate(int year,int month,int day){
cld.set(year,month-1,day);
}
//获取该日是一年当中的第几天
public int getDay(){
return cld.get(6);
}
//获取该日是星期几
public String getDate(){
int date = cld.get(7);
return getWeekday(date);
}
//判断解析一周7天的值
public String getWeekday(int dayofweek){
switch(dayofweek){
case 1: return "星期日";
case 2: return "星期一";
case 3: return "星期二";
case 4: return "星期三";
case 5: return "星期四";
case 6: return "星期五";
case 7: return "星期六";
default:return "error";
}
}
public static void main(String[] args) {
GetBirth gb = new GetBirth();
gb.setDate(gb.year, gb.month, gb.day);
System.out.println(gb.getDay());
System.out.println(gb.getDate());
}
}
热心网友
时间:2023-10-06 04:19
直接用现在的年 - 输入的年 就能算出来