Date类的重点是:fastTime--毫秒表示
The class Date represents a specific instant in time, with millisecond precision.
GregorianCalendar类的重点是:日期使用“年月日时分秒"表示
GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.
日历格式显示的重点:
(1)求出当前月份的第一天的星期数与本地区每周第一天的星期数
(2)根据(1),打印\t
(3)循环打印本月的日期,直到月份不是本月为止
代码如下:
package com.study.calendardemo;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class CalendarDemo {
public static void main(String[] args) {
// 构造对象d作为当前日期
// GregorianCalendar d = new GregorianCalendar(2013, 10, 20);
GregorianCalendar d = new GregorianCalendar();
System.out.println("请输入日期格式:(年月日,格式:2012-9-10):");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
sc.close();
//System.out.println(s);
String[] date = s.split("-");
//System.out.println(Integer.parseInt(date[1]));
d.set(Calendar.YEAR, Integer.parseInt(date[0]));
d.set(Calendar.MONTH, (Integer.parseInt(date[1])-1));
d.set(Calendar.DATE, Integer.parseInt(date[2]));
int month = d.get(Calendar.MONTH);// 当前月份如12显示为11
int today = d.get(Calendar.DAY_OF_MONTH);// 当前日期如10
System.out.println("当前月份:" + (month + 1) + "月 当前日期:" + today + "日");
// 将对象d设置为当前月的第一天
d.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("设置后的日期:" + (d.get(Calendar.MONTH) + 1) + "月"
+ d.get(Calendar.DAY_OF_MONTH) + "日");
// 设置后的日期(即本月第一天)是本周第几天,美国从周日开始,周日=1 周一=2 周六=7
int weekday = d.get(Calendar.DAY_OF_WEEK);
System.out.println("本月第一天是星期 " + weekday);// 6为周五
// 获得本地区 周的第一天
int firstDayOfWeek = d.getFirstDayOfWeek();// 美国周日为每周的第一天即周日=1 周一=2 周六=7
System.out.println("本地区 周的第一天是星期 " + firstDayOfWeek);// 1为周日
// 打印日历头部标题
// 获取星期的简写形式
String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
for (int i = firstDayOfWeek, j = 0; j
System.out.printf("%s\t", weekdayNames[i++]);// weekday此时为星期的第一天,一般是上月日期
}
System.out.println();
// 打印当前月星期的第一个天到当前日期的星期数之间的间隔
for (int i = firstDayOfWeek; i
System.out.print("\t");
}
// 只要循环中日期没有超过本月,循环继续
while (d.get(Calendar.MONTH) == month) {
int day = d.get(Calendar.DAY_OF_MONTH);
// 如过打印的日期与当前日期同一天,则打印*
if (day == today)
System.out.print("*");
else
System.out.print(" ");
System.out.printf("%d\t", day);
// 天数+1
d.add(Calendar.DAY_OF_MONTH, 1);
weekday = d.get(Calendar.DAY_OF_WEEK);
// 如果星期数等于星期的第一天,则换行
if (weekday == firstDayOfWeek) {
System.out.println();
}
}
if (weekday != firstDayOfWeek) {
System.out.println();
}
}
}