[英]SimpleDateFormat Parsing error with AM/PM
我試圖將輸入字符串日期解析為Date。 它無法檢測輸入中的AM / PM標簽。 它應該增加指定日期和返回日期的時間。 但它無法解析AM / PM標簽。 03:00 PM在日期中解析為03:00:00。 應該是15:00:00。
輸出:日期:星期二12月22日03:00:00 UTC 2015日歷:星期二12月22日星期二11:15:00結果:2015-12-22 11:15 AM
我使用錯誤的日期格式嗎?
這是我的代碼:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.