Calender 中的add和set用法

在项目中,会经常需要获取过去几天,几月,几年前的时间,所以这里采用Calendar中的add方法获取。

源码:Adds or subtracts the specified amount of time to the given calendar field,based on the calendar's rules. For example, to subtract 5 days fromthe current time of the calendar, you can achieve it by calling:

意思就是根据日历规则,向给定日历字段添加或减去指定的时间。第一个参数为当前的时间(时分秒,年月日),第二个参数是需要加减的时间。

add:

例如:我需要获取当前七天前的时间:param1 当前日期,param2 七天前日期,采用负数;

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
//过去七天
c.setTime(new Date());
c.add(Calendar.DATE, - 7);
Date d = c.getTime();
String day = format.format(d);
LOGGER.info("当前时间的前七天时间为:" + day);

运行结果:

set:

主要是设置自己需要的时间,没有具体用过。不多描述

Calendar c = Calendar.getInstance();

// 获取月
int year = c.get(Calendar.YEAR);
// 获取月
int month = c.get(Calendar.MONTH);
// 获取日
c.set(2018, 01, 12);
// 获取月
year = c.get(Calendar.YEAR);
// 获取月
month = c.get(Calendar.MONTH);
// 获取日
date = c.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值