LocalDateTime获取时间类
LocalDateTime获取时间类是java8提供的一个新的获取时间类,该类可以获取任意格式的时间,使用非常方便。
1. 获取当前当前时间
public void timeNow() {
//输出当前时间
LocalDateTime dateTime = LocalDateTime.now();
System.out.println(dateTime);
}
2.获取指定格式时间
public void formatDateTime() {
//格式化格式
String format = "YYYY-MM-dd hh:mm:ss";
// DateTimeFormatter.ofPattern方法根据指定的格式输出时间
String formatDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
System.out.println(formatDateTime);
}
3.获取某个日期的时间
获取某个日期的时间可以通过选择不同的plus方法一直选择下去。
public void getDateTime() {
//获取当前日期后一天的后一个小时
LocalDateTime dateTime = LocalDateTime.now().plusDays(1).plusHours(1);
System.out.println(dateTime);
//格式化格式
String format = "YYYY-MM-dd hh:mm:ss";
//获取当前日期后三天以后3小时的时间并格式化输出
String formatDate = LocalDateTime.now().plusDays(3).plusHours(3).format(DateTimeFormatter.ofPattern(format));
System.out.println(formatDate);
}
```