Java_常用类14_Calendar类

Calendar类:它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段 之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。

1.    日历类,封装了所有的日历字段值,通过统一的方法根据传入不同的日历字段可以获取值。

2.    如何得到一个日历对象呢?

  Calendar rightNow = Calendar.getInstance();// 使用默认时区和语言环境获得一个日历。返回的 Calendar 基于当前时间,使用了默认时区和默认语言环境。

  本质返回的是子类对象

3.    成员方法

  A: public int get(int field):返回给定日历字段的值。日历类中的每个日历字段都是静态的成员变量,并且是int类型

  B: public void add(int field,int amount): 根据日历的规则,为给定的日历字段添加或减去指定的时间量。

  C: public final void set(int year,int month,int date): 设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。

public class CalendarDemo {
    public static void main(String[] args) {
        // 其日历字段已由当前日期和时间初始化:
        Calendar c = Calendar.getInstance();
        // 获取年
        int year = c.get(Calendar.YEAR);
        // 获取月
        int month = c.get(Calendar.MONTH);
        // 获取日
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // 2017年4月1日
        // Month 值是基于 0 的。例如,0 表示 January。
        /*********************************************************************************/
        // 三年前的今天
        c.add(Calendar.YEAR, -3);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // 2014年4月1日
        /*********************************************************************************/
        // 5年后的10天前
        c.add(Calendar.YEAR, 5);
        c.add(Calendar.DATE, -10);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // 2019年3月22日
        /*********************************************************************************/
        c.set(2011, 11, 11);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // 2011年12月11日
    }
}

4.    案例:

/*
* 计算任意一年的二月有多少天
* 分析:
*         A:键盘录入任意的年份
*         B:设置日历对象的年月日
*             年就是A输入的数据
*             月是2
*             日是1
*         C:把时间往前推一天,就是2月的最后一天
*         D:获取这一天输出即可
*/
public class CalendarDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入年份:");
        int year = sc.nextInt();
        // 设置日历对象的年月日
        Calendar c = Calendar.getInstance();
        c.set(year, 2, 1); // 其实是这一年的3月1日
        c.add(Calendar.DATE, -1); // 把时间往前推一天,就是2月的最后一天
        System.out.println(c.get(Calendar.DATE));
    }
}

猜你喜欢

转载自www.cnblogs.com/zhaolanqi/p/9239244.html