localDateTime,localDate,localTime的使用
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeTest {
public static void main(String[] args) {
getFormatting();
getStr();
getLocalDate();
getLocalTime();
}
private static void getLocalTime() {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime localTime = LocalTime.now();
String time = localTime.format(pattern);
System.out.println(time);
String str = "12:45:56";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime localTime1 = LocalTime.parse(str, pattern);
System.out.println(localTime1);
}
private static void getLocalDate() {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.now();
String localDate = date.format(pattern);
System.out.println(localDate);
String time = "2019-12-26";
DateTimeFormatter DatePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(time, DatePattern);
System.out.println(dateTime);
}
private static void getStr() {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.now();
String strTime = dateTime.format(dateTimeFormatter);
System.out.println(strTime);
}
private static void getFormatting() {
String time = "2019-12-26 12:15:56";
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(time, pattern);
System.out.println(dateTime);
}
}
示例
1.获取最近一年的月份
LocalDate today = LocalDate.now();
DateTimeFormatter form = DateTimeFormatter.ofPattern("yyyy-MM");
String[] date = {
form.format(today.minusMonths(11)),
form.format(today.minusMonths(10)),
form.format(today.minusMonths(9)),
form.format(today.minusMonths(8)),
form.format(today.minusMonths(7)),
form.format(today.minusMonths(6)),
form.format(today.minusMonths(5)),
form.format(today.minusMonths(4)),
form.format(today.minusMonths(3)),
form.format(today.minusMonths(2)),
form.format(today.minusMonths(1)),
form.format(today)};
System.out.println(Arrays.asList(date));
2.获取3天前的时间
LocalDateTime now = LocalDateTime.now();
LocalDateTime threeDaysAgo = now.minusDays(3);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = threeDaysAgo.format(formatter);
System.out.println("Three days ago was: " + formattedTime);