编写一个java方法,计算你出生的那一天是星期几?并显示从出生到现在每年过生日那天的星期数
时间: 2024-05-29 19:10:46 浏览: 37
利用Java计算某个日期是星期几
5星 · 资源好评率100%
public class BirthdayCalculator {
public static void main(String[] args) {
String birthday = "1996-01-01";
int dayOfWeek = getDayOfWeek(birthday);
System.out.println("你出生的那一天是星期" + dayOfWeek);
printBirthdayOfWeek(birthday);
}
/**
* 计算指定日期是星期几
*
* @param date 指定日期,格式为yyyy-MM-dd
* @return 星期几,1表示星期一,7表示星期日
*/
public static int getDayOfWeek(String date) {
int[] weeks = {7, 1, 2, 3, 4, 5, 6};
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek < 0) {
dayOfWeek = 0;
}
return weeks[dayOfWeek];
}
/**
* 显示从出生到现在每年过生日那天的星期数
*
* @param birthday 出生日期,格式为yyyy-MM-dd
*/
public static void printBirthdayOfWeek(String birthday) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("从出生到现在每年过生日那天的星期数:");
int nowYear = calendar.get(Calendar.YEAR);
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
while (nowYear <= currentYear) {
int dayOfWeek = getDayOfWeek(sdf.format(calendar.getTime()));
System.out.println(nowYear + "年:" + dayOfWeek);
calendar.add(Calendar.YEAR, 1);
nowYear = calendar.get(Calendar.YEAR);
}
}
}
阅读全文