java.util.Calendar类:日历类
1、Calendar类
Calendar 是一个日历类,里面提供了很多操作日历字段的方法(TAER, MONTH, DAY_OF_MONTH, HOUR)
Calendar 类无法直接创建对象使用,里面有一个静态方法getInstance(), 该方法返回了Calendar 类的子类对象
static Calendar getInstance(),使用默认语言环境获得一个日历
package cn.day12.demo02;
import java.util.Calendar;
public class Demo01Calendar {
public static void main(String[] args) {
Calendar instance = Calendar.getInstance(); //多态
System.out.println(instance);
//结果: //java.util.GregorianCalendar[time=1651581749616,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=1,DAY_OF_MONTH=3,DAY_OF_YEAR=123,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=8,HOUR_OF_DAY=20,MINUTE=42,SECOND=29,MILLISECOND=616,ZONE_OFFSET=28800000,DST_OFFSET=0]
}
}
2、常用方法
常用方法 成员方法的参数package cn.day12.demo02;
import java.util.Calendar;
public class Demo02Calendar {
public static void main(String[] args) {
// demo01();
/*
public int get(int field):返回给定日历字段的值
参数:传递指定的日历字段(YEAR MONTH...)
返回值:日历字段代表的具体值
*/
demo02();
/*
public int set(int field, int value):将给定的日历字段设置为给定值
*/
}
private static void demo01(){
//使用getInstance方法获取Calendar对象
Calendar c = Calendar.getInstance();
int i = c.get(Calendar.YEAR);
System.out.println(i);
System.out.println(c.get(Calendar.MONTH)); //西方月份0-11月,东方1-12
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DATE));
}
private static void demo02(){
Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR,2023);
instance.set(Calendar.MONTH, 6);
//同时设置年月日,使用set 的重载方法
// instance.set(8888,8,9);
int i = instance.get(Calendar.YEAR);
System.out.println(i); //2023
System.out.println(instance.get(Calendar.MONTH)); //西方月份0-11月,东方1-12 , 6
}
}
结果:
2022
4
3
3
2023
6
网友评论