java日历类(calendar),可输出年月日等等,以及和Date相互转化
日历创建对象:
- Calendar类为抽象类,不可实例化
- 方式一:
- 父类引用指向类对象
- Calendar cal = new GregorianCalendar();
- 方式二:
- Calendar cal = Calendar.getInstance();
获取年,月,日,时,分,秒 ,毫秒 ,一年的第几天,一年的第几周,一个月的第几周,一周的第几天(周索引)
月:(0-11 ) 表示1-12月 ,周索引:(1-7) 表示的周日到周六 ,周日表示1,周一时2,以此类推,周六是7
读出日历
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int date1 = cal.get(Calendar.DATE);
int date2 = cal.get(Calendar.DAY_OF_MONTH);
int hour1 = cal.get(Calendar.HOUR);
int hour2 = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
//毫秒
int millSec = cal.get(Calendar.MILLISECOND);
//一年的第几天
int dayIndex = cal.get(Calendar.DAY_OF_YEAR);
//一年的第几周
int weekIndex = cal.get(Calendar.WEEK_OF_YEAR);
//一个月的第几周
int weekIndex2 = cal.get(Calendar.WEEK_OF_MONTH);
//一周的第几天
int weekIndex3 = cal.get(Calendar.DAY_OF_WEEK);
写入日历
cal.set(Calendar.YEAR, 2019);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DATE, 28);
cal.set(Calendar.DAY_OF_MONTH, 28);
/**
* 和Date之间的相互转换
* Calendar---》Date getTime()
* Date --->Calendar setTime()
* @author Administrator
*
*/
public class TestCalendar07 {
public static void main(String[] args) {
Calendar cal = new GregorianCalendar();
Date date = cal.getTime();
System.out.println("date对象:"+date);
System.out.println("============================");
Date date2 = new Date();
cal.setTime(date2);
System.out.println("日历对象:"+cal);
}
}