- / 또는 허용하는 Java 날짜 형식. 날짜 내 분리기로
-
22-07-2019 - |
문제
다음 형식 중 하나 일 수있는 날짜를 구문 분석하는 가장 좋은 방법은 무엇입니까?
"dd-MM-yyyy HH:mm"
"dd/MM/yyyy HH:mm"
"dd.MM.yyyy HH:mm"
3 개의 단순한 형태를 만들지 않고 각각에 대한 구문 분석.
감사
해결책
소스 문자열을 표준 형식으로 "조정"하는 것이 가장 쉽습니다.
if (text.length() == 16)
{
if ((text.charAt(2) == '/' && text.charAt(5) == '/') ||
(text.charAt(2) == '.' && text.charAt(5) == '.'))
{
text = text.substring(0, 2) + "-" + text.substring(3, 5)
+ "-" + text.substring(6);
}
}
그런 다음 "-"를 사용하여 형식 문자열을 사용하십시오.
이것은 매우 구체적이며 교체 만하십시오 바로 그거죠 원치 않는 부작용을 피하기 위해 관심있는 캐릭터.
다른 팁
먼저 두 개의 교체 작업을 실행하여 세 형식을 모두 단일 형식으로 줄일 수 있습니까?
당신은 사용할 수 있습니다 Apache Commons lang dateutils.parsedate
import java.text.ParseException;
import org.apache.commons.lang.time.DateUtils;
public class Test {
public static void main(String[] args) throws ParseException {
String[] values = new String[]{"31-12-2009 12:00", "31/12/2009 12:00", "31.12.2009 12:00"};
String[] parsePatterns = new String[]{"dd-MM-yyyy HH:mm", "dd/MM/yyyy HH:mm", "dd.MM.yyyy HH:mm"};
for (String value : values) {
System.out.println(DateUtils.parseDate(value, parsePatterns));
}
}
}
글쎄, 내부적으로 그것은 단순한 형태를 만들지 만 그게 무슨 문제가 있습니까?
성폭력은 어때 :
"\\d\\d[./-]\\d\\d[./-]\\d\\d\\d\\d \\d\\d:\\d\\d"
코드에서 이것은 다음과 같은 것을 의미합니다.
Pattern pattern =
Pattern.compile("(\\d\\d)([./-])(\\d\\d)([./-])(\\d\\d\\d\\d) (\\d\\d):(\\d\\d)");
Matcher matcher =
pattern.matcher("31-07-1983 15:30");
if (matcher.find() && matcher.group(2).equals(matcher.group(4))) {
int day = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(3));
int year = Integer.parseInt(matcher.group(5));
int hour = Integer.parseInt(matcher.group(6));
int minute = Integer.parseInt(matcher.group(7));
}
정기적 인 표현으로 스스로하는 것 :
public class SpecialDateFormat
{
private final static Pattern PATTERN = Pattern.compile("(\\d{2})[\\.\\/\\-](\\d{2})[\\.\\/\\-](\\d{4}) (\\d{2}):(\\d{2})");
public static Date parse(String text) throws ParseException {
Matcher m = PATTERN.matcher(text);
if (m.matches()) {
int dd = Integer.parseInt(m.group(1));
int mm = Integer.parseInt(m.group(2));
int yy = Integer.parseInt(m.group(3));
int hh = Integer.parseInt(m.group(4));
int mi = Integer.parseInt(m.group(5));
// NOTE: Checking if values are in valid ranges omitted
Calendar cal = Calendar.getInstance();
cal.set(yy, mm - 1, dd, hh, mi, 0);
return cal.getTime();
}
else {
throw new ParseException("Unparseable date: " + text, 0);
}
}
}
그러나 이것은 다른 분리기를 혼합 할 수 있습니다. 예를 들어 "17-09/2009 12:00"이 허용됩니다.
ParseExact는 다양한 형식을 사용할 수 있습니다. 여전히 모든 형식을 지정해야하지만 단일 작업입니다.
제휴하지 않습니다 StackOverflow