1、表示时间点的类Date在java.util.Date中
获得当前时间点:System.out.println("当前时间" + new Date());
将时间点转化为字符串:String s = new Date().toString();
2、日历表示使用的类GregorianCalendar在java.util.GregorianCalendar中
GregorianCalendar now = new GregorianCalendar();
获得月份:int month = now.get(Calendar.MONTH);
获得当日是一周中的第几天:int weekday = now.get(Calendar.DAY_OF_WEEK);
修改日历的时间 now.set(field, amount); now.add(field, amount);
日历转时间点:Date time = now.getTime();
时间点转日历:now.setTime(time);
示例小程序:输出当前一个月的日历
package test;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main {
public static void main(String args[]) {
//GreforianCalendar示例程序
GregorianCalendar d = new GregorianCalendar();//获取当前时间的信息
int today = d.get(Calendar.DAY_OF_MONTH);//获取当日的日期
int month = d.get(Calendar.MONDAY);//获取月份
d.set(Calendar.DAY_OF_MONTH,1);//将时间设置为每月的1号
int weekday = d.get(Calendar.DAY_OF_WEEK);//查询本月1号是一周中的第几天
int firstDayOfWeek = d.getFirstDayOfWeek();//查询当前地区一周的第一天
int indent= 0;
while(weekday != firstDayOfWeek) {//通过逐渐将日期-1,来找出本月开始应该空几个日期
indent++;
d.add(Calendar.DAY_OF_MONTH, -1);
weekday = d.get(Calendar.DAY_OF_WEEK);
}
//DateFormatSymbols在java.text.DateFormatSymbols中
//getShortWeekdays获得当前地区的一周的简称
String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
do{
System.out.printf("%4s", weekdayNames[weekday]);
d.add(Calendar.DAY_OF_MONTH,1);
weekday = d.get(Calendar.DAY_OF_WEEK);
}while(weekday != firstDayOfWeek);
System.out.println();
//输出日期,当天的日期后要打印*
for(int i = 0; i < indent; i++)
System.out.printf(" ");
d.set(Calendar.DAY_OF_MONTH,1);
do{
int day = d.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d", day);
if(day == today) System.out.print("*");
else System.out.print(" ");
d.add(Calendar.DAY_OF_MONTH, 1);
weekday = d.get(Calendar.DAY_OF_WEEK);
if(weekday == firstDayOfWeek) System.out.println();
} while(d.get(Calendar.MONDAY) == month);
if(weekday != firstDayOfWeek) System.out.println();
}
}