亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 LocalDate 將一個日期更改為另一種日期格式

使用 LocalDate 將一個日期更改為另一種日期格式

慕容森 2023-07-13 14:33:55
我有以下輸入作為Map<String,String>1) MM dd yyyy = 08 10 20192) dd MM yyyy = 10 05 20193) dd MM yyyy = 05 10 20084) yyyy dd MM =  2001 24 01我想將所有這些日期轉換為“yyyy-MM-dd”格式目前,我正在使用for (String eachFormat : formats) {    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(eachFormat);    try {        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");        Date inputDate = simpleDateFormat.parse(parsedDate.get(eachFormat));        return targetFormat.format(inputDate);    } catch (ParseException e) {        LOGGER.error(e);    }}但“simpleDateFormat.parse()”將轉換并使用時區給我日期。我在轉換時不需要時區。我想直接將一種日期格式轉換為另一種日期格式。我正在探索 LocalDate 作為 java 8 功能。但如果我嘗試就會失敗DateTimeFormatter target = DateTimeFormatter.ofPattern(eachFormat);LocalDate localDate = LocalDate.parse(parsedDate.get(eachFormat),target);請幫助我使用 LocalDate 和 DateTimeFormatter。編輯 1:好的,我對輸入地圖示例不好,這是我在程序中得到的實際地圖1) MM dd yy = 8 12 20192) dd MM yy = 4 5 20073) yy dd MM = 2001 10 8我猜識別并向我提供這張地圖的人正在使用 SimpleDate 格式化程序,因為我假設 SimpleDateFormatter 可以將日期“8 12 2019”識別為“MM dd yy”或“M dd yyyy”或“MM d yy”或“ MM d yyyy”....但“LocalDate”非常嚴格,它不解析日期"8 12 2019" for "dd MM yy"它嚴格解析當且僅當日期格式"8 12 2019" is "d MM yyyy"……現在我該怎么辦?
查看完整描述

1 回答

?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

是的,老的,SimpleDateFormat解析的時候麻煩,一般都不太關注格式模式字符串中模式字母的個數。DateTimeFormatter確實如此,這通常是一個優點,因為它可以更好地驗證字符串。MM月份需要兩位數。yy需要兩位數的年份(例如 2019 年為 19)。由于您需要能夠解析一位數字的月份、月份中的某一天以及四位數字的年份,因此我建議我們修改格式模式字符串以準確地說明DateTimeFormatter這一點。我正在改變MM到M,dd到d,yy到y。這將導致DateTimeFormatter不必擔心位數(一個字母基本上意味著至少一位數字)。


    Map<String, String> formattedDates = Map.of(

            "MM dd yy", "8 12 2019",

            "dd MM yy", "4 5 2007",

            "yy dd MM", "2001 10 8");


    for (Map.Entry<String, String> e : formattedDates.entrySet()) {

        String formatPattern = e.getKey();

        // Allow any number of digits for each of year, month and day of month

        formatPattern = formatPattern.replaceFirst("y+", "y")

                .replace("dd", "d")

                .replace("MM", "M");

        DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern(formatPattern);

        LocalDate date = LocalDate.parse(e.getValue(), sourceFormatter);

        System.out.format("%-11s was parsed into %s%n", e.getValue(), date);

    }

該片段的輸出是:


8 12 2019   was parsed into 2019-08-12

4 5 2007    was parsed into 2007-05-04

2001 10 8   was parsed into 2001-08-10


查看完整回答
反對 回復 2023-07-13
  • 1 回答
  • 0 關注
  • 240 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號