从字符串中取任意日期或者时间格式字符正则
String regex = “[1-9]\d{3}\D(0[1-9]|1[0-2]|[1-9])\D(0[1-9]|[1-2][0-9]|3[0,1]|[1-9]|)\D{0,2}((0[0-9]|1[0-9]|2[0-3]|[1-9])\D([0-5][0-9]|[0-9])\D([0-5][0-9]|[0-9])|((0[0-9]|1[0-9]|2[0-3]|[1-9])\D([0-5][0-9]|[0-9])))?”
将任意时间格式字符转成LocalDateTime
/**
* 将时间字符串任意格式转成LocalDateTime
* @param timeStr
* @return 时分秒
*/
public static LocalDateTime getLocalDateTime(String timeStr){
String parse = timeStr.replaceFirst("[0-9]{4}([^0-9]?)", "yyyy$1");
parse = parse.replaceFirst("([^0-9]?)[0-9]{1,2}([^0-9]?)", "$1MM$2");
parse = parse.replaceFirst("([^0-9]?)[0-9]{1,2}( ?)", "$1dd$2");
parse = parse.replaceFirst("( )[0-9]{1,2}([^0-9]?)", "$1HH$2");
parse = parse.replaceFirst("([^0-9]?)[0-9]{1,2}([^0-9]?)", "$1mm$2");
parse = parse.replaceFirst("([^0-9]?)[0-9]{1,2}([^0-9]?)", "$1ss$2");
DateFormat format = new SimpleDateFormat(parse);
Date date = null;
try {
date = format.parse(timeStr);
} catch (ParseException e) {
log.error(e.getMessage(),e);
}
LocalDateTime time = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
return time;
}
如果有更简单的办法或者哪里有错误请告知谢谢