简体   繁体   English

SimpleDateFormat 返回错误值

[英]SimpleDateFormat Return wrong value

I have two different date format from multiple source i want to format but its 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;
}

and output is和 output 是

12/01/0012 06:37:01 PM 2012 年 12 月 1 日下午 6:37:01

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

could you please help me to fix it你能帮我修一下吗

your input on day 1 is malformed, it should be yyyy-MM-dd, but you pass as dd-MM-yyyy.您在第 1 天的输入格式错误,应该是 yyyy-MM-dd,但您传递的是 dd-MM-yyyy。 Code here代码在这里

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