Java에서 모든 날짜 구문 분석
나는이 질문이 꽤 많이 요구된다는 것을 알고 있으며 분명히 임의의 날짜를 구문 분석 할 수 없습니다. 그러나 python-dateutil 라이브러리는 내가 던지는 모든 날짜를 구문 분석 할 수 있으며 날짜 형식 문자열을 알아내는 데 전혀 노력을 기울이지 않아도됩니다. Joda 시간은 항상 훌륭한 Java 날짜 파서로 판매되지만 형식을 선택하거나 직접 작성하기 전에 날짜 형식을 결정해야합니다. DateFormatter.parse (mydate)를 호출하고 마술처럼 Date 객체를 다시 가져올 수는 없습니다.
예를 들어 "Wed Mar 04 05:09:06 GMT-06 : 00 2009"날짜는 python-dateutil로 올바르게 구문 분석됩니다.
import dateutil.parser
print dateutil.parser.parse('Wed Mar 04 05:09:06 GMT-06:00 2009')
그러나 다음 Joda 시간 호출은 작동하지 않습니다.
String date = "Wed Mar 04 05:09:06 GMT-06:00 2009";
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime dt = fmt.parseDateTime(date);
System.out.println(date);
고유 한 DateTimeFormatter를 만드는 것은 올바른 형식 문자열과 함께 SimpleDateFormatter를 사용하는 것과 동일한 것처럼 보이기 때문에 목적에 맞지 않습니다.
python-dateutil과 같이 Java에서 날짜를 구문 분석하는 비슷한 방법이 있습니까? 나는 오류에 대해 신경 쓰지 않고 대부분 완벽하기를 원합니다.
가장 좋은 방법은 날짜 형식 패턴과 일치하거나 무차별 대입을 수행하기 위해 정규식에 도움을 요청하는 것입니다.
몇 년 전에 나는 그 일을 하는 약간 어리석은 DateUtil
수업 을 썼다 . 관련성 추출은 다음과 같습니다.
private static final Map<String, String> DATE_FORMAT_REGEXPS = new HashMap<String, String>() {{
put("^\\d{8}$", "yyyyMMdd");
put("^\\d{1,2}-\\d{1,2}-\\d{4}$", "dd-MM-yyyy");
put("^\\d{4}-\\d{1,2}-\\d{1,2}$", "yyyy-MM-dd");
put("^\\d{1,2}/\\d{1,2}/\\d{4}$", "MM/dd/yyyy");
put("^\\d{4}/\\d{1,2}/\\d{1,2}$", "yyyy/MM/dd");
put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}$", "dd MMM yyyy");
put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}$", "dd MMMM yyyy");
put("^\\d{12}$", "yyyyMMddHHmm");
put("^\\d{8}\\s\\d{4}$", "yyyyMMdd HHmm");
put("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{2}$", "dd-MM-yyyy HH:mm");
put("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{2}$", "yyyy-MM-dd HH:mm");
put("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{2}$", "MM/dd/yyyy HH:mm");
put("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}$", "yyyy/MM/dd HH:mm");
put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{2}$", "dd MMM yyyy HH:mm");
put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{2}$", "dd MMMM yyyy HH:mm");
put("^\\d{14}$", "yyyyMMddHHmmss");
put("^\\d{8}\\s\\d{6}$", "yyyyMMdd HHmmss");
put("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd-MM-yyyy HH:mm:ss");
put("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}$", "yyyy-MM-dd HH:mm:ss");
put("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "MM/dd/yyyy HH:mm:ss");
put("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}$", "yyyy/MM/dd HH:mm:ss");
put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd MMM yyyy HH:mm:ss");
put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd MMMM yyyy HH:mm:ss");
}};
/**
* Determine SimpleDateFormat pattern matching with the given date string. Returns null if
* format is unknown. You can simply extend DateUtil with more formats if needed.
* @param dateString The date string to determine the SimpleDateFormat pattern for.
* @return The matching SimpleDateFormat pattern, or null if format is unknown.
* @see SimpleDateFormat
*/
public static String determineDateFormat(String dateString) {
for (String regexp : DATE_FORMAT_REGEXPS.keySet()) {
if (dateString.toLowerCase().matches(regexp)) {
return DATE_FORMAT_REGEXPS.get(regexp);
}
}
return null; // Unknown format.
}
(기침, 이중 중괄호 초기화, 기침, 100 자 최대 길이에 모두 맞추기위한 것이 었습니다.))
새로운 regex 및 dateformat 패턴으로 쉽게 확장 할 수 있습니다.
귀하의 목적에 맞는 Natty 라는 멋진 라이브러리가 있습니다 .
Natty is a natural language date parser written in Java. Given a date expression, natty will apply standard language recognition and translation techniques to produce a list of corresponding dates with optional parse and syntax information.
You can also try it online!
What I have seen done is a Date util class that contains several typical date formats. So, when DateUtil.parse(date) is called, it tries to parse the date with each date format internally and only throws exceptions if none of the internal formats can parse it.
It is basically a brute force approach to your problem.
You could try dateparser.
It can recognize any String automatically, and parse it into Date, Calendar, LocalDateTime, OffsetDateTime correctly and quickly(1us~1.5us
).
It doesn't based on any natural language analyzer
or SimpleDateFormat
or regex.Pattern
.
With it, you don't have to prepare any appropriate patterns like yyyy-MM-dd'T'HH:mm:ss.SSSZ
or yyyy-MM-dd'T'HH:mm:ss.SSSZZ
:
Date date = DateParserUtils.parseDate("2015-04-29T10:15:00.500+0000");
Calendar calendar = DateParserUtils.parseCalendar("2015-04-29T10:15:00.500Z");
LocalDateTime dateTime = DateParserUtils.parseDateTime("2015-04-29 10:15:00.500 +00:00");
All works fine, please enjoy it.
참고URL : https://stackoverflow.com/questions/3389348/parse-any-date-in-java
'programing tip' 카테고리의 다른 글
안드로이드 다운로드 바이너리 파일 문제 (0) | 2020.10.29 |
---|---|
Tomcat 기본 URL 리디렉션 (0) | 2020.10.29 |
로드되지 않는 VSTO 추가 기능의 문제를 해결하는 방법은 무엇입니까? (0) | 2020.10.29 |
태그를 (0) | 2020.10.29 |
C # : MSTest 단위 테스트에서 "예외가 발생하지 않음"을 어떻게 확인합니까? (0) | 2020.10.29 |