可以先参考我前面相差天数算法,把总的天数对7取余即可得到星期几,任何把一个月的一周遍历打出来
/*输入你的出生年月日,算出你出生了多少天*/
package KH08;
import java.time.Year;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Test01{
public static void main(String[] args) {
String[] strWeek = {"日\t","一\t","二\t","三\t","四\t","五\t","六\t"};//输出没有天数的部分
Scanner s = new Scanner(System.in);
System.out.println("请输入你要输入的年份");
int year1 = s.nextInt();
System.out.println("请输入你要输入的月份");
int month1 = s.nextInt();
int day = 1;
//创建一个我的日历对象
MyCalendar m1 = new MyCalendar();
int daysum = m1.calculateDay(year1 , month1);//计算所有天数,daysum%7可以求出星期几
//计算这个月的天数
if (month1==2){
if (((year1 % 4 == 0)&&(year1 % 100 != 0) ||(year1 % 400 == 0))){
day = 29;
}
else {
day = 28;
}
}
else if (month1 == 4 || month1 == 6 || month1 == 9 || month1 == 11 ){
day = 30;
}
else{
day = 31;
}
System.out.println();
System.out.println();
System.out.println(year1 + "年" + month1 + "月");
System.out.println();
for (int i = 0; i < strWeek.length;i++){
System.out.print(strWeek[i]);
}
System.out.println();
int week = (daysum % 7) +1;//{7,1,2,3,4,5,6}
for (int i = 0; i < week;i++){
System.out.print("\t");
}
for (int i = 1; i <= day; i++){
System.out.print(i + "\t");
if((daysum+1 + i)%7 == 0)//前面天数+现在天数%7是星期天自动换行
{
System.out.println();
}
}
}
}
class MyCalendar{
public MyCalendar() {
}
/*
* 用来计算从1900年到你输入的天数
* 返回值:一共多少天
* */
public int calculateDay(int year1,int month1){
Scanner s = new Scanner(System.in);
//1900-1-1星期1
int year2 = 1900;
int month2 =1;
int day2 = 1;
int day = 0; //计算所有天数
//计数相差年之间的所有天数
for (int year = year2;year < year1;year++ ){ //year是相隔的那年,即遍历相差的每一年
if (((year % 4 == 0)&&(year % 100 != 0) ||(year % 400 == 0))){
day = day + 366;//是闰年为366天
}
else {
day = day + 365;//是闰年为365天
}
}
//去掉你那年还没有出身的所有天数
for (int month = 1;month < month2;month++){
if (month==2){
if (((year2 % 4 == 0)&&(year2 % 100 != 0) ||(year2 % 400 == 0))){
day = day - 29;
}
else {
day = day - 28;
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11 ){
day = day - 30;
}
else{
day = day - 31;
}
}
day = day -1;//去掉你那年还没有出身的那月所有天数
//加上现在时间已经过了的天数
for (int month = 1;month < month1;month++){
if (month==2){
if (((year1 % 4 == 0)&&(year1 % 100 != 0) ||(year1 % 400 == 0))){
day = day + 29;
}
else {
day = day + 28;
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11 ){
day = day + 30;
}
else{
day = day + 31;
}
}
day = 1 +day;
System.out.println(day);
return day;
}
}