LocalDateTime日期格式化和指定日期的时分秒
代码语言:javascript复制package com.example.core.mydemo.date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* now=2023-06-30
* after=2023-07-04
* afterTime=2023-07-04T00:00:01
* dateFormat=06/30-07/01
*/
public class LocalDateTest {
public static final String YYYYMMDDHHMMSSS_PATTERN = "yyyyMMddHHmmss";
public static final String DEFAULT_PATTERN_NEW_SHORT = "MM/dd";
public static void main(String[] args) {
LocalDate now = LocalDate.now();
LocalDate after = now.plusDays(4);
LocalDateTime afterTime = after.atTime(0,0,1);
System.out.println("now=" now);
System.out.println("after=" after);
System.out.println("afterTime=" afterTime);
String startTime = "20230630163000";
String endTime = "20230701163000";
LocalDateTime startLdt = parseStringToDateTime(startTime,YYYYMMDDHHMMSSS_PATTERN);
LocalDateTime endLdt = parseStringToDateTime(endTime,YYYYMMDDHHMMSSS_PATTERN);
String rentStr = formatDateTime(startLdt,DEFAULT_PATTERN_NEW_SHORT);
String revertStr = formatDateTime(endLdt,DEFAULT_PATTERN_NEW_SHORT);
String rentViewFormat = rentStr "-" revertStr;
System.out.println("dateFormat=" rentViewFormat);
}
public static LocalDateTime parseStringToDateTime(String time, String format) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(time, df);
}
public static String formatDateTime(LocalDateTime dateTime, String pattern) {
if (dateTime == null) {
return null;
}
if (pattern == null || pattern.isEmpty()) {
pattern = YYYYMMDDHHMMSSS_PATTERN;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return dateTime.format(formatter);
}
}