AM/PM 的 SimpleDateFormat 解析错误

SimpleDateFormat Parsing error with AM/PM

我正在尝试将输入字符串日期解析为日期。它无法在输入中检测到 AM/PM 标签。 它应该将时间添加到指定日期和 return 日期。 但它无法解析 AM/PM 标签。 03:00 PM 在 Date 中解析为 03:00:00。应该是 15:00:00.

输出: 日期:12 月 22 日星期二 03:00:00 UTC 2015 日历:12 月 22 日星期二 11:15:00 UTC 2015 结果:2015 年 12 月 22 日 11:15 上午

我使用的日期格式有误吗?

这是我的代码:

import java.util.*;
import java.text.*;
public class Main {
   public static void main(String[] args) throws Exception {
      System.out.println("Result : "+Main.addHoursToDate("2015-12-22 03:00 `enter code here`PM",8,15,0));
   }

   public static String addHoursToDate(String date, int hoursToAdd, int minsToAdd, int secToAdd){
        String result = "";
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm aa");
            Date dt = sdf.parse(date);

            System.out.println("Date : " + dt.toString());

            Calendar cl = Calendar.getInstance();
            cl.setTime(dt);
            cl.add(Calendar.HOUR_OF_DAY, hoursToAdd);
            cl.add(Calendar.MINUTE, minsToAdd);
            cl.add(Calendar.SECOND, secToAdd);

            SimpleDateFormat dfCal = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");

            result = Main.formatDate(cl.getTime().toString(),"EEE MMM dd HH:mm:ss z yyyy","yyyy-MM-dd HH:mm aa");

            System.out.println("Calender : " + cl.getTime().toString());

        }catch(Exception e){
            return e.toString();
        }
        return result;
    }

  public static String formatDate(String date, String currentFormat, String requiredFormat) throws Exception {
        String result = "";
        boolean flag = false;
        try {
            SimpleDateFormat currentFormatter = new SimpleDateFormat(currentFormat);
            Date currentDate = currentFormatter.parse(date);

            flag = date.equals(currentFormatter.format(currentDate));
            if (!flag){
                throw new Exception();  // We are throwing this exception because the date has been parsed "successfully"  
                // but still we are not sure that it has been parsed "correctly"!!!
            }
            SimpleDateFormat requiredFormatter = new SimpleDateFormat(requiredFormat);
            result = requiredFormatter.format(currentDate);
        }catch (Exception e){
            return "";
        }

        return result;
    }

}

自己得到答案:

我需要使用

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");

而不是

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm aa");

H : 用于 24 小时制。

参考 https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html