Java8实现日期时间与字符串之间转换工具类
import java. time. LocalDateTime;
import java. time. format. DateTimeFormatter;
public class TimeUtils {
public static final String FORMATTER_TYPE_ONE = "yyyy-MM-dd HH:mm:ss" ;
public static final String FORMATTER_TYPE_TWO = "yyyy/MM/dd HH:mm:ss" ;
public static LocalDateTime ISO8601FormatLocalDateTime ( String timeStr) {
try {
org. joda. time. format. DateTimeFormatter dateTimeFormatter = ISODateTimeFormat. dateTime ( ) ;
org. joda. time. LocalDateTime localDateTime = dateTimeFormatter. parseLocalDateTime ( timeStr) ;
return LocalDateTime. parse ( localDateTime. toString ( ) ) ;
} catch ( Exception e) {
return LocalDateTime. now ( ) ;
}
}
public static LocalDateTime StrFormat ( String timeStr, String format) {
try {
DateTimeFormatter formatter = DateTimeFormatter. ofPattern ( format) ;
return LocalDateTime. parse ( timeStr, formatter) ;
} catch ( Exception e) {
return LocalDateTime. now ( ) ;
}
}
public static LocalDateTime StrFormat ( String timeStr) {
try {
DateTimeFormatter formatter = DateTimeFormatter. ofPattern ( FORMATTER_TYPE_ONE) ;
return LocalDateTime. parse ( timeStr, formatter) ;
} catch ( Exception e) {
return LocalDateTime. now ( ) ;
}
}
public static String dateTimeFormat ( LocalDateTime localDateTime, String format) {
try {
DateTimeFormatter formatter = DateTimeFormatter. ofPattern ( format) ;
return formatter. format ( localDateTime) ;
} catch ( Exception e) {
return LocalDateTime. now ( ) . toString ( ) ;
}
}
public static String dateTimeFormat ( LocalDateTime localDateTime) {
try {
DateTimeFormatter formatter = DateTimeFormatter. ofPattern ( FORMATTER_TYPE_ONE) ;
return formatter. format ( localDateTime) ;
} catch ( Exception e) {
return LocalDateTime. now ( ) . toString ( ) ;
}
}
}