欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Calendar时间接口操作

程序员文章站 2024-03-14 14:42:40
...
public static void main(String[] args) {
	SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Calendar cal = Calendar.getInstance();
    //获取时间
    System.out.println("年:" + cal.get(Calendar.YEAR));
    System.out.println("月:" + (cal.get(Calendar.MONTH) + 1));
    System.out.println("日:" + cal.get(Calendar.DAY_OF_MONTH));
    System.out.println("时:" + cal.get(Calendar.HOUR_OF_DAY));
    System.out.println("分:" + cal.get(Calendar.MINUTE));
    System.out.println("秒:" + cal.get(Calendar.SECOND));
    System.out.println("当前时间"+fmt.format(cal.getTime()));//2019-08-11 11:25:36
    // 赋值时间,注意月份下标从0开始,所以取月份要+1
    cal.set(1998, 4, 10, 23,59,59);
    System.out.println("设置后时间"+fmt.format(cal.getTime()));//1998-05-10 23:59:59
    // 或者6个字段分别进行设置,由于月份下标从0开始赋值月份要-1
    cal.set(Calendar.YEAR, 1998);
    cal.set(Calendar.MONTH, 4);
    cal.set(Calendar.DAY_OF_MONTH, 10);
    cal.set(Calendar.HOUR_OF_DAY, 00);
    cal.set(Calendar.MINUTE, 00);
    cal.set(Calendar.SECOND, 00);
    System.out.println("设置后时间"+fmt.format(cal.getTime()));//1998-05-10 00:00:00

    //年加1减1
    cal.add(Calendar.YEAR, 1);
    System.out.println("年+1:"+fmt.format(cal.getTime()));//1999-05-10 00:00:00
    cal.add(Calendar.YEAR, -1);
    System.out.println("年-1:"+fmt.format(cal.getTime()));//1998-05-10 00:00:00

    //月加1减1
    cal.add(Calendar.MONTH, 1);
    System.out.println("月+1:"+fmt.format(cal.getTime()));//1998-06-10 00:00:00
    cal.add(Calendar.MONTH, -1);
    System.out.println("月-1:"+fmt.format(cal.getTime()));//1998-05-10 00:00:00

    //天加1减1
    cal.add(Calendar.DAY_OF_MONTH, 1);
    System.out.println("天+1:"+fmt.format(cal.getTime()));//1998-05-11 00:00:00
    cal.add(Calendar.DAY_OF_MONTH, -1);
    System.out.println("天-1:"+fmt.format(cal.getTime()));//1998-05-10 00:00:00

    //时加1减1
    cal.add(Calendar.HOUR_OF_DAY, 1);
    System.out.println("时+1:"+fmt.format(cal.getTime()));//1998-05-10 01:00:00
    cal.add(Calendar.HOUR_OF_DAY, -1);
    System.out.println("时-1:"+fmt.format(cal.getTime()));//1998-05-10 00:00:00

    //分加1减1
    cal.add(Calendar.MINUTE, 1);
    System.out.println("分+1:"+fmt.format(cal.getTime()));//1998-05-10 00:01:00
    cal.add(Calendar.MINUTE, -1);
    System.out.println("分+1:"+fmt.format(cal.getTime()));//1998-05-10 00:00:00
    //秒加1减1
    cal.add(Calendar.SECOND, 1);
    System.out.println("秒+1:"+fmt.format(cal.getTime()));//1998-05-10 00:00:01
    cal.add(Calendar.SECOND, -1);
    System.out.println("秒-1:"+fmt.format(cal.getTime()));//1998-05-10 00:00:00
}

 

相关标签: Calendar 示例