SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String newData = sdf.format(new Date());
System.out.println("当前时间="+newData);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(calendar.WEEK_OF_YEAR, -1); //一周前
System.out.println("一周前="+sdf.format(calendar.getTime()));
calendar.add(calendar.YEAR, +1); //一年后
System.out.println(sdf.format(calendar.getTime()));
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
calendar.add(calendar.DAY_OF_YEAR, -2); //两天前
System.out.println("两天前="+sdf2.format(calendar.getTime()));
calendar.add(calendar.MINUTE, +10); //十分钟后
System.out.println("十分钟后="+sdf2.format(calendar.getTime()));
calendar = Calendar.getInstance(); //初始化时间
/*也可以使用 new Date()初始化
*calendar = Calendar.setTime(new Date();
*/
System.out.println("初始化后="+sdf2.format(calendar.getTime()));
// 显示年份
int year = calendar.get(Calendar.YEAR);
System.out.println("年份 = " + String.valueOf(year));
// 显示月份 (从0开始, 实际显示要加一)
int month = calendar.get(Calendar.MONTH);
System.out.println("月份= " + (month + 1));
// 今年的第 N 天
int DAY_OF_YEAR = calendar.get(Calendar.DAY_OF_YEAR);
System.out.println("今年第几天 = " + DAY_OF_YEAR);
// 本月第 N 天
int DAY_OF_MONTH = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("本月第几天 = " + String.valueOf(DAY_OF_MONTH));
结果:
当前时间=2017-04-28
一周前=2017-04-21
2018-04-21
两天前=2018-04-19 11:13:19:986
十分钟后=2018-04-19 11:23:19:986
初始化后=2017-04-28 11:13:19:989
年份 = 2017
月份= 4
今年第几天 = 118
本月第几天 = 28