java日历
闰年(二月为二十九天,一年就三百六十六天,年份能被4整除但不能被100整除的或者能被400整除的是闰年),平年(二月为二十八天,一年三百六十五天)
蔡勒(Zeller)公式是一个计算星期的公式.随便给一个日期,就能用这个公式推算出是星期几.蔡勒公式如下:
w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1
公式中的符号含义如下,w:星期;c:世纪-1;y:年(两位数);m:月(m大于等于3,小于等于14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月来计算,比如2003年1月1日要看作2002年的13月1日来计算);d:日;[ ]代表取整,即只要整数部分。(C是世纪数减一,y是年份后两位,M是月份,d是日数。1月和2月要按上一年的13月和 14月来算,这时C和y均按上一年取值。)
算出来的W除以7,余数是几就是星期几。如果余数是0,则为星期日。
然后是java日历的源码:
package calendar;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("请输入年份:");
int year=input.nextInt();
System.out.print("请输入月份:");
int month=input.nextInt();
input.close();
if(month==2)
{
//闰年month有29天
if((year%4==0&&year%400!=0)||year%100==0)
{
reinforcePrintf(year-1,14,29);
}
//平年month有28天
else {
reinforcePrintf(year-1,14,28);
}
}else {
//小月day有30天
if(month==4||month==6||month==9||month==11)
{
reinforcePrintf(year,month,30);
}
//大月day有31天
else {
//是否是1月
if(month==1)
{
reinforcePrintf(year-1,13,31);
}
else {
reinforcePrintf(year,month,31);
}
}
}
}
//打印日历的方法
private static void reinforcePrintf(int year,int month,int day)
{
System.out.println(year+"年"+month+"月的日历为:\n");
int center=year/100;
year=year-center*100;
int w=year+year/4+center/4-2*center+(13*(month+1))/5;//计算某年某月一日的星期
w=w%7;
System.out.println("天\t一\t二\t三\t四\t五\t六\t");//打印日历表头
int j=1;//j在这里记录1到day打印到了哪里
for(int i=0;i<=6;i++)//根据w开始打印日历的第一行
{
if(i<w)
{
System.out.print(" \t");//在w之前没有记录
}else {
System.out.print(j+"\t");//在w之后,打印day的记录j
j++;
}
}
System.out.print("\n");//转到日历的下一行
for(center=j,j=1;center<=day;center++)//在这里center表示剩下的j到day打印到了哪里,j记录一行只打印7个
{
System.out.print(center+"\t");//打印日历当前记录center
j++;
if(j>7)//每打印完7个换行
{
j=j%7;
System.out.print("\n");
}
}
}
}
测试结果如下:
源码属于个人原创,没有参照任何代码,但某些知识概念有所借鉴