簡體   English   中英

解析奇怪的日期字符串?

[英]Parse strange Date String?

我實際上正在研究掃描PDF的項目。 在這些PDF上有日期,但是它似乎比平時更復雜,因為它是法語日期,並且格式可能有所不同(月為3/4個字母),例如:

MERMAR17-LUNJUIL14 ...

而且,我想要以下輸出:

17/03-14/07 ...

我的代碼示例:

String date = "MARJUIN2" 
DateFormat dateFormat = new SimpleDateFormat("EEE'MMM'dd", Locale.FRENCH);
        try {
            Date varDate = dateFormat.parse(date);         
            cellString = varDate.toString();
            SimpleDateFormat newDF = new SimpleDateFormat("dd/MM", Locale.FRENCH);
            cellString = newDF.format(varDate);
            }
            catch(Exception e) {
                    e.printStackTrace();
                }

可能嗎 ? 還是n /?

好的,這里是沒有Java-8或任何外部庫的解決方案(盡管會更容易)。 該解決方案基於以下假設:您的輸入始終以日期名稱開頭,其長度始終固定為3個字符(“ MER”,“ LUN”等)。 通過選擇默認年份為2000,該解決方案考慮了2月29日可能出現的leap日。

您可能會問為什么要付出如此大的努力。 好吧,原因是您的文本資源與JDK(或CLDR)的文本資源有所不同。 因此,您必須設置自己的專用文本資源。 我在解決方案中使用的月份名稱僅是猜測。 您應該根據需要調整這些名稱。

static final String[] MONTHS =
    { "JAN", "FEV", "MAR", "AVR", "MAI", "JUIN", "JUIL", "AOÛ", "SEP", "OCT", "NOV", "DEC" };

public static void main(String[] args) throws ParseException {

    String s = "MERMAR17 - LUNJUIL14";
    String[] parts = s.split(" - ");

    SimpleDateFormat parser = new SimpleDateFormat("EEEMMMdd yyyy", Locale.FRENCH);
    System.out.println(parser.format(new GregorianCalendar(2015, 2, 18).getTime()));
    // shows deviation between your input and JDK-resources: mer.mars18 2015

    int m0 = parse(parts[0]);
    int m1 = parse(parts[1]);
    Date d0 =
        new GregorianCalendar(
            2000,
            m0,
            Integer.parseInt(parts[0].substring(3 + MONTHS[m0].length()))
        ).getTime();
    Date d1 =
        new GregorianCalendar(
            2000,
            m1,
            Integer.parseInt(parts[1].substring(3 + MONTHS[m1].length()))
        ).getTime();

    SimpleDateFormat format = new SimpleDateFormat("dd/MM");
    String result = format.format(d0) + " - " + format.format(d1);
    System.out.println(result); // 17/03 - 14/07

}

private static int parse(String input) throws ParseException {
    for (int i = 0; i < 12; i++) {
        if (input.substring(3).startsWith(MONTHS[i])) {
            return i;
        }
    }
    throw new ParseException("Cannot parse month abbreviation in: " + input, 3);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM