2017-06-01 180 views
4

我有類從其他類接收字符串格式的日期。它現在接收兩個不同的格式基於字符串選擇日期格式

格式1:YYYY_MM_DD

格式2:EEE MMM DD HH:MM:SSžYYYY

現在我想寫接收到該字符串的方法,並將其轉換進入這樣的「DDMMMYYYY」

+1

您的意思是可以處理format1和format2然後導致DDMMMYYYY? –

+0

@ΦXocę웃Пepeúpaツ是的,確切地說 – Raj

+0

我寧願使用兩個'DateTimeFormatter'對象。嘗試使用其中一個解析爲「LocalDate」,如果拋出DateTimeParseException,則使用另一個解析。最後使用第三種格式轉換爲所需的格式。記住:年份是小寫'yyyy'或'uuuu',月份的日期是小寫'dd'。並給你的格式化器適當的區域設置。 –

回答

4

要求的格式,您可以嘗試蠻力解析捕獲異常:

編輯:

使用java8 API(適應的格式,因爲你需要/想)

public String convertDateFormatJ8(String format) { 
    String retFormat = "ddMMyyy"; 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_dd_MM][yyyy-MM-dd HH:mm]"); 
    try { 
     LocalDateTime localDate = LocalDateTime.parse(format, formatter); 
     return localDate.format(DateTimeFormatter.ofPattern(retFormat)); 
    } catch (DateTimeParseException ex) { 
     System.err.println("impossible to parse to yyyy-MM-dd HH:mm"); 
    } 
    try { 
     LocalDate localDate = LocalDate.parse(format, formatter); 
     return localDate.format(DateTimeFormatter.ofPattern(retFormat)); 
    } catch (DateTimeParseException ex) { 
     System.err.println("impossible to parse to yyyy_dd_MM"); 
    } 

    return null; 

} 

老的Java版本

public String convertDateFormat(String format) { 
     DateFormat df1 = new SimpleDateFormat("YYYY_MM_DD"); 
     DateFormat df2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); 
     DateFormat dfResult = new SimpleDateFormat("DDMMMYYYY "); 
     Date d = null; 
     try { 
      d = df1.parse(format); 
      return dfResult.format(d); 
     } catch (ParseException e) { 
      System.err.println("impossible to parse to " + "YYYY_MM_DD"); 
     } 
     try { 
      d = df2.parse(format); 
      return dfResult.format(d); 
     } catch (ParseException e) { 
      System.err.println("impossible to parse to " + "EEE MMM dd HH:mm:ss z yyyy"); 
     } 
     return null; 
    } 

如果你給其他任何無效的字符串,返回的字符串將是空的!

+1

你錯過了將日期轉換爲像DDMMMYYYY這樣的字符串的第三個DateFormat ;-) – aexellent

+0

Holy pattern,Thanks !! –

+0

請不要教年輕人使用過時的SimpleDateFormat和朋友。今天我們好多了。例如見[Andriy Rymar的回答](https://stackoverflow.com/a/44302191/5772882)。 –

3

您可以使用此方法,並在圖案聲明可選部分:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_MM_dd][EEE MMM dd HH:mm:ss Z yyyy]", Locale.ENGLISH); 

formatter將解析日期爲兩個模式,然後你可以很容易地將其轉換爲所需要的格式。

P.S.我已經測試過它,但不知道哪個日期應該可以解析爲EEE MMM dd HH:mm:ss Z yyyy模板。因此,只需使用它並使用Java 8方法(Java時間)

+0

[這裏是](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)解釋如何使用它。 –

+1

在格式模式字符串中,第一種格式應該寫爲yyyy_MM_dd,小寫字母y和d(大寫字母Y代表以周爲單位的年份,僅在週數中有用;大寫字母D代表年份中的日期)。 –

+0

@AndriyRymar As Ole V.V.評論,你在這個答案中的代碼*非常*破碎。請修復或刪除。 –