/**
* @author YoonaLt
* LocalDateTime 與 LocalDate 都提供了 plus***(加),minus***(減)等方法,
* 可以方便的獲取與目標日期相距幾年,幾月,幾星期,幾天,幾小時,幾分,幾秒的時間.
*/
public class DateUtils {
private static String DETAIL_FORMAT_STRING = "yyyy-MM-dd HH:mm:ss";
private static String PROBABLY_FORMAT_STRING = "yyyy-MM-dd";
private static String DETAIL_REGEX = "(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])";
private static String PROBABLY_REGEX = "\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0|1])";
/**
* 格式化 LocalDateTime
*
* @param localDateTime 將要格式化的日期
* @return 例如, 2020-04-03 14:12:02
*/
public static String localDateTimeToString(LocalDateTime localDateTime) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DETAIL_FORMAT_STRING);
return localDateTime == null ? null : dateTimeFormatter.format(localDateTime);
}
/**
* 格式化 LocalDate
*
* @param localDate 將要格式化的日期
* @return 例如, 2020-04-03
*/
public static String localDateToString(LocalDate localDate) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(PROBABLY_FORMAT_STRING);
return localDate == null ? null : dateTimeFormatter.format(localDate);
}
/**
* 字符串格式化,字符串必須符合 "yyyy-MM-dd HH:mm:ss" 格式,當字符串非法時,返回 null
* yyyy-MM-dd 24:00:00 格式的字符串也視爲非法
*
* @param s 將要 LocalDateTime 化的字符串
* @return LocalDateTime
*/
public static LocalDateTime stringToLocalDateTime(String s) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DETAIL_FORMAT_STRING);
return s == null || "".equals(s) || !Pattern.matches(PROBABLY_REGEX + " " + DETAIL_REGEX, s) ?
null : LocalDateTime.parse(s, dateTimeFormatter);
}
/**
* 字符串格式化,字符串必須符合 yyyy-MM-dd 格式,當字符串非法時,例如 201s-00-35 時,返回 null
*
* @param s 將要 LocalDate 化的字符串
* @return LocalDate
*/
public static LocalDate stringToLocalDate(String s) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(PROBABLY_FORMAT_STRING);
return s == null || "".equals(s) || !Pattern.matches(PROBABLY_REGEX, s) ?
null : LocalDate.parse(s, dateTimeFormatter);
}
}
由於本人水平有限,難免會出現錯誤,歡迎指正.