簡體   English   中英

SimpleDateFormat 返回錯誤值

[英]SimpleDateFormat Return wrong value

我有兩種不同的日期格式,來自多個我想格式化的來源,但它返回錯誤的值。

    String d1 = getFormattedDate("06-07-2022 18:37:01");
    String d2 = getFormattedDate("2020-11-21 18:45:15");
    System.out.println(d1);
    System.out.println(d2);

private static String getFormattedDate(String date) {
    try {
        SimpleDateFormat targetSdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf1.parse(date);
            return targetSdf.format(date1);
        } catch (Exception e) {
            SimpleDateFormat sdf5 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date date5 = sdf5.parse(date);
            return targetSdf.format(date5);
        }
    } catch (Exception e) {

    }
    return date;
}

和 output 是

2012 年 12 月 1 日下午 6:37:01

2020 年 11 月 21 日下午 6:45:15

你能幫我修一下嗎

您在第 1 天的輸入格式錯誤,應該是 yyyy-MM-dd,但您傳遞的是 dd-MM-yyyy。 代碼在這里

private static String getFormattedDate(String date) {
    try {
        SimpleDateFormat targetSdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf1.parse(date);
            return targetSdf.format(date1);
        } catch (Exception e) {
            SimpleDateFormat sdf5 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date date5 = sdf5.parse(date);
            return targetSdf.format(date5);
        }
    } catch (Exception e) {

    }
    return date;
}
public static void main(String[] args) throws ParseException {
    String d1 = getFormattedDate("2022-07-06 18:37:01");
    String d2 = getFormattedDate("2020-11-21 18:45:15");
    System.out.println(d1);
    System.out.println(d2);

}

暫無
暫無

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

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