万年历

本文详细介绍了万年历算法的实现过程,包括判断闰年、获取月份天数、计算从1900年1月1日到指定年月的总天数,并通过示例代码展示了如何获取给定日期的前一个月底与1900年1月1日的总天数差,最后计算并输出该天数对7的余数作为空格数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**

 * 我的万年历

 * 

 * 1.190011日:星期一:

 * 

 * 2.2014,2月的日历: 2014131日到190011日的总天数 除,余数就是空格数

 * 

 * 

 * 整年:1900-2013年整年:—+365,+366 正月:1月到month-1的月份的总天数

 * 

 * @author Administrator

 * 

 */

import java.util.Scanner;

public class MyCalendar {
	/**
	 * 判断给定的年份是否是闰年
	 * 
	 * @param year
	 * @return
	 */
	public static boolean loopYear(int year) {
		if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 每个月的天数
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getDayOfMonth(int year, int month) {
		int day = 0;
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			day = 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			day = 30;
			break;
		case 2:
			if (MyCalendar.loopYear(year)) {
				day = 29;
			} else {
				day = 28;
			}
		}
		return day;
	}

	/**
	 * 求给定年份及月份的上一个月底,到1900年1月1日的总天数
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getDays(int year, int month) {
		int sum = 0;
		// 整年
		for (int i = 1900; i < year; i++) {
			if (MyCalendar.loopYear(i)) {
				sum += 366;
			} else {
				sum += 365;
			}
		}
		System.out.println("---->" + sum);
		// 整月
		for (int i = 1; i < month; i++) {
			sum += getDayOfMonth(year, i);
		}
		return sum;
	}

	/**
	 * 求1900,1,1日距离当前月份上一个月份的总体按数,除以7的余数,就是空格数
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getFirstDay(int year, int month) {
		return MyCalendar.getDays(year, month) % 7;
	}

	public static void printCalendar(int year, int month) {
		System.out.println("星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t星期日");
		int first = getFirstDay(year, month);
		for (int i = 0; i < first; i++) {
			System.out.print("\t");
		}
		int day = getDayOfMonth(year, month);// 要打印的月份,有多少天
		for (int i = 1; i <= day; i++) {
			System.out.print(i + "\t");
			if ((i + first) % 7 == 0) {
				System.out.println();
			}
		}

	}

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		// System.out.println("请输入一个年份:");
		// int year = scan.nextInt();
		// System.out.println("请输入一个月份:");
		// int month = scan.nextInt();
		// MyCalendar.printCalendar(year, month);
		System.out.println("-->" + (getFirstDay(2000, 4)));
		System.out.println(getDays(2000, 4) + getDayOfMonth(2000, 4));

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值