万年历
Calendar
- Calendar类位于java.util下,是一个工具类,能够帮我们轻松的实现日期的查询和转换。
实例化
- Calendar有一个静态方法 getInstance() 可以取得Calendar的实例,通过对实例的操作可以获得我们想要的数据。
Calendar calendar = Calendar.getInstance();
常量
常量 | 描述 |
---|
Calendar.YEAR | 年份 |
Calendar.MONTH | 月份 |
Calendar.DATE | 日期 |
Calendar.DAY_OF_MONTH | 日期,和上面的字段意义完全相同 |
Calendar.HOUR | 12小时制的小时 |
Calendar.HOUR_OF_DAY | 24小时制的小时 |
Calendar.MINUTE | 分钟 |
Calendar.SECOND | 秒 |
Calendar.DAY_OF_WEEK | 返回星期几 |
Calendar类对象信息的设置
Set设置
Calendar c = Calendar.getInstance();
c.set(calendar1.getYear(),calendar1.getMonth()-1,1);
Add设置
Calendar c1 = Calendar.getInstance();
c1.add(Calendar.DATE, 10);
c1.add(Calendar.DATE, -10);
获取时间对应的周几
int week = c.get(Calendar.DAY_OF_WEEK);
输出标题及当月最大天数
System.out.println("日\t一\t二\t三\t四\t五\t六");
for(int i = 1;i < week;i++ ){
System.out.print(" ");
}
int maxMonthDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
附录(源码)
package HomeWork;
import java.util.Calendar;
import java.util.Scanner;
public class Calendar1 {
private int year;
private int month;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
if (month >= 1 && month <= 12)
this.month = month;
else {
System.out.println("月份必须是1-12");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calendar1 calendar1 = new Calendar1();
System.out.print("请输入年份: ");
calendar1.setYear(scanner.nextInt());
System.out.print("请输入月份: ");
calendar1.setMonth(scanner.nextInt());
Calendar c = Calendar.getInstance();
c.set(calendar1.getYear(),calendar1.getMonth()-1,1);
int week = c.get(Calendar.DAY_OF_WEEK);
System.out.println("日\t一\t二\t三\t四\t五\t六");
for(int i = 1;i < week;i++ ){
System.out.print(" ");
}
int maxMonthDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
for(int i = 1 ; i <= maxMonthDay;i++){
int date = c.get(Calendar.DATE);
if((i+week-2)%7==0){
System.out.println();
}
System.out.printf("%-4d",date);
c.add(Calendar.DATE,1);
}
}
}