2017-11-25 1 views
1

아래 코드를 사용하여 다른 형식으로 날짜를 구문 분석합니다.다른 형식의 Java 날짜

trubel은 첫 번째 형식을 취하고 적합하지 않은 경우에도 날짜를 구문 분석합니다.

public static Date parseDate(String date) { 
    date = date.replaceAll("[-,.;:_/&()+*# ']", "-"); 
    System.out.print(date); 
    List<String> formatStrings = Arrays.asList("d-M-y","y-M-d"); 
    for (String formatString : formatStrings) { 
     try { 
      System.out.println(new SimpleDateFormat(formatString).parse(date)); 
      return new SimpleDateFormat(formatString).parse(date); 
     } catch (Exception e) { 
     } 
    } 
    return null; 
} 

콘솔 : 첫 번째 형식에 allways 분석 않는 이유

1994-02-13 
Wed Jul 18 00:00:00 CEST 2018 

또는

13-02-1994 
Sun Feb 13 00:00:00 CET 1994 

그래서 내가 얻을하지 않습니다?

+2

. 형식이 지정되어 있지 않습니다. – Jay

답변

2

다음은 jshell의 간단한 예제입니다. "d-M-y"는 기본적으로 관대하기 때문에 둘 다 구문 분석합니다. setLenient(false)을하면 다른 형식의 날짜는 예외가됩니다.

| Welcome to JShell -- Version 9.0.1 
| For an introduction type: /help intro 

jshell> java.text.SimpleDateFormat dmy = new java.text.SimpleDateFormat("d-M-y"); 
dmy ==> [email protected] 

jshell> dmy.parse("13-02-1994") 
$2 ==> Sun Feb 13 00:00:00 CST 1994 

jshell> dmy.parse("1994-02-13") 
$3 ==> Wed Jul 18 00:00:00 CDT 2018 

jshell> dmy.isLenient() 
$4 ==> true 

jshell> dmy.setLenient(false) 

jshell> dmy.parse("1994-02-13") 
| java.text.ParseException thrown: Unparseable date: "1994-02-13" 
|  at DateFormat.parse (DateFormat.java:388) 
|  at (#6:1) 

참고로, 자바 8 + API의 방법은이 작업을 수행합니다 : 당신이 문자열을 구문 분석하고 있기 때문에

jshell> java.time.format.DateTimeFormatter dmy = java.time.format.DateTimeFormatter.ofPattern("dd-MM-yyyy"); 
dmy ==> Value(DayOfMonth,2)'-'Value(MonthOfYear,2)'-'Value(YearOfEra,4,19,EXCEEDS_PAD) 

jshell> java.time.LocalDate.parse("13-02-1994", dmy) 
$2 ==> 1994-02-13 

jshell> java.time.LocalDate.parse("1994-02-13", dmy) 
| java.time.format.DateTimeParseException thrown: Text '1994-02-13' could not be parsed at index 2 
|  at DateTimeFormatter.parseResolved0 (DateTimeFormatter.java:1988) 
|  at DateTimeFormatter.parse (DateTimeFormatter.java:1890) 
|  at LocalDate.parse (LocalDate.java:428) 
|  at (#3:1) 
+2

탱크 꽤 좋은 답변 이군요. –

+2

확실히 Java 8 방식을 권장합니다. 이걸 제공해 주셔서 감사합니다. –

2

루프가 첫 번째 return 문에서 멈추고 루프에서 return 문을 제거하면 날짜 형식이 뒤집어집니다.

편집 : 의견 요청에 따라 :

public static Date parseDate(String date) { 
    Date dateToReturn = null; 
    date = date.replaceAll("[,\\.;:_/&\\(\\)\\+\\*# ']", "-"); 
    String formatString = "d-M-y"; 
    if (date.matches("\\d{4}-\\d{2}-\\d{2}")) { 
     formatString = "y-M-d"; 
    } 
    try { 
     dateToReturn = new SimpleDateFormat(formatString).parse(date); 
    } catch (Exception e) { 
     System.out.println("the given date does not math this format " + formatString); 
    } 
    return dateToReturn; 
} 

을 여기에 당신은 두 가지 형식이 생각보다.

+0

날짜를 반환하고 싶지만 예외가 있으면 반환해야합니까? –

+0

괜찮습니까? 그러나 어떤 형식을 기반으로합니까? 왜냐하면 두 가지 형식이 혼란 스럽기 때문에 –

+0

웹 백엔드에서 이것을 사용하고 브라우저에서 다른 형식을 사용할 수 있습니다. –

관련 문제