@Test public void test1() { Calendar cal = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(df.format(cal.getTime())); }
该程序的运行结果如下:
2021-11-10 15:38:58
@Test public void test2() { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR);//获取年份 int month = cal.get(Calendar.MONTH) + 1;//获取月份 注意:会比当前时间少一个月 int day = cal.get(Calendar.DATE);//获取日 int hour = cal.get(Calendar.HOUR_OF_DAY);//小时 int minute = cal.get(Calendar.MINUTE);//分 int second = cal.get(Calendar.SECOND);//秒 System.out.println("year: " + year); System.out.println("month: " + month); System.out.println("day: " + day); System.out.println("hour: " + hour); System.out.println("minute: " + minute); System.out.println("second: " + second); }
该程序的运行结果如下:
year: 2021 month: 11 day: 10 hour: 15 minute: 39 second: 47
@Test public void test3() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println("当前时间:\n" + df.format(cal.getTime())); cal.add(Calendar.YEAR, 1); System.out.println("加一年:\n" + df.format(cal.getTime())); cal.add(Calendar.MONTH, 1); System.out.println("在加一个月:\n" + df.format(cal.getTime())); cal.add(Calendar.DAY_OF_MONTH, 1); System.out.println("在加一天:\n" + df.format(cal.getTime())); cal.add(Calendar.DAY_OF_MONTH, -1); System.out.println("在减一天:\n" + df.format(cal.getTime())); cal.set(Calendar.HOUR_OF_DAY, 0); System.out.println("在设置小时为0:\n" + df.format(cal.getTime())); cal.set(Calendar.MINUTE, 0); System.out.println("在设置分钟为0:\n" + df.format(cal.getTime())); cal.set(Calendar.SECOND, 0); System.out.println("在设置秒为0:\n" + df.format(cal.getTime())); }
该程序的运行结果如下:
当前时间: 2021-11-10 15:40:17 加一年: 2022-11-10 15:40:17 在加一个月: 2022-12-10 15:40:17 在加一天: 2022-12-11 15:40:17 在减一天: 2022-12-10 15:40:17 在设置小时为0: 2022-12-10 00:40:17 在设置分钟为0: 2022-12-10 00:00:17 在设置秒为0: 2022-12-10 00:00:00
@Test public void test1() { Calendar cal = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(df.format(cal.getTime())); }
该程序的运行结果如下:
2021-11-10 15:38:58