首页 > 代码库 > 日期练习
日期练习
import java.util.*;
//import java.text.*;
class RiLi
{
int days;
public void jisuan(){
Calendar calendar = Calendar.getInstance();
Scanner sc=new Scanner(System.in);
System.out.print("请输入年份");
int year = sc.nextInt();
System.out.print("请输入月份");
int m = sc.nextInt();
int month = m-1;//计算月要减一
calendar.set(Calendar.YEAR, year);//用户输入的年
calendar.set(Calendar.MONTH, month); //用户输入的月
calendar.set(Calendar.DATE, 0); //没有输入天数
if (((year%4==0&&year%100!=0)||(year%400==0))&&m==2)//闰年2月的天数
{
days = 29;
}else {
days = panduan(month+1);//传过去判断时要恢复到输入的值
}
System.out.println(year + "年" + (month + 1) + "月的日历:");
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
for (int count = 1;count<=days;count++)
{
calendar.add(Calendar.DAY_OF_MONTH, 1); //这个月的第一天 运行一次就加一
//int day = calendar.getTime().getDay(); //取出这一天 .getDay()过时了.
int day = calendar.get(Calendar.DAY_OF_WEEK);
// System.out.print(day+"\t");
if (count ==1) {
for (int i = 0; i < day-1; i++) {
System.out.print("\t");
}
}
if ( (day-1)== 0) {
System.out.println(); //出现星期天 就换行,外国人周天是一个周开始
}
//System.out.print(calendar.getTime().getDate() + "\t"); //每月多少号 // getDate()过时了
System.out.print(count + "\t");
}
}
public static int panduan(int m) {
int days = 0;
switch (m) {
case 2:
days = 28;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 0;
}
return days;
}
}
class Work1
{
public static void main(String[] args)
{
RiLi r = new RiLi();
r.jisuan();
}
}
日期练习