文章目录
一、时间获取
1.1 获取完整的时间
@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
1.2 分别获取年、月、日、时、分、秒
@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
1.3 修改当前时间
@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
二、日期格式化
2.1 格式中字母的含义
- yyyy:年
- MM:月
- dd:日
- hh:1~12小时制(1-12)
- HH:24小时制(0-23)
- mm:分
- ss:秒
- S:毫秒
- z:表示时区
2.2 格式化日期
@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