Java获取当前时间并格式化

主要有以下方法

使用Calendar

1
2
3
4
5
6
7
Calendar now = Calendar.getInstance();
System.out.println("年:" + now.get(Calendar.YEAR));
System.out.println("月:" + (now.get(Calendar.MONTH) + 1));
System.out.println("日:" + now.get(Calendar.DAY_OF_MONTH));
System.out.println("时:" + now.get(Calendar.HOUR_OF_DAY));
System.out.println("分:" + now.get(Calendar.MINUTE));
System.out.println("秒:" + now.get(Calendar.SECOND));

使用Date

1
2
3
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("当前时间:" + sdf.format(d));

使用jdk8新的时间apiLocalDateTimeLocalDateLocalTime

jdk8 日期与时间: LocalDateTime
1
2
3
4
5
6
LocalDateTime nowDateTime = LocalDateTime.now();
System.out.println(nowDateTime);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(dateTimeFormatter.format(nowDateTime));
// 反着使用也可以
System.out.println(nowDateTime.format(dateTimeFormatter));
jdk8 日期: LocalDate
1
2
3
4
5
6
LocalDate nowDate = LocalDate.now();
System.out.println(nowDate);
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(dateFormatter.format(nowDate));
// 反着使用也可以
System.out.println(nowDate.format(dateFormatter));
jdk8 时间: LocalTime
1
2
3
4
5
6
LocalTime nowTime = LocalTime.now();
System.out.println(nowTime);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(timeFormatter.format(nowTime));
// 反着使用也可以
System.out.println(nowTime.format(timeFormatter));