我正在編寫一個程序來計算java中使用Joda Time的年齡差異,並且在計算hoursBetween()時,它不會考慮考慮AM和PM。這裏是我的代碼:Joda Time在使用小時和12小時不工作時不考慮AM/PM
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String DOB = "";
String NOW = "";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date dob = null;
Date now = null;
try {
System.out
.println("Enter the date and time of your birth using the mm/dd/yyyy and the hh:mm AM/PM format: ");
DOB = scan.nextLine();
System.out
.println("Enter the date and time using the mm/dd/yyyy and the hh:mm AM/PM format: ");
NOW = scan.nextLine();
dob = format.parse(DOB);
now = format.parse(NOW);
DateTime dob1 = new DateTime(dob);
DateTime now1 = new DateTime(now);
System.out.print("You are ");
System.out.print(Years.yearsBetween(dob1, now1).getYears()
+ " years, ");
System.out.print(Months.monthsBetween(dob1, now1).getMonths() % 12
+ " months, ");
System.out.print(Days.daysBetween(dob1, now1).getDays() % 60
+ " days, ");
System.out.print(Hours.hoursBetween(dob1, now1).getHours() % 12
+ " hours, ");
System.out.print("and "
+ Minutes.minutesBetween(dob1, now1).getMinutes() % 60
+ " minutes old!");
} catch (Exception e) {
e.printStackTrace();
}
}}
如果我的出生日期輸入爲「2014年1月1日12:00 AM」我的當前時間輸入「2014年1月1日下午12:00的」結果是:「你是0歲,0個月,0小時,0歲。」應該是12個小時。有沒有辦法來解決這個問題?我的猜測是有一些方法來實現halfdayOfDay()方法,並調用它在我的DateTime的,但我還沒有找到它...感謝您的任何幫助!(順便說一句,我使用12小時一天的輸入,但在分析它仍然接受13:00的時候就應該最大程度的發揮在12:00!)
爲什麼要用'SimpleDateFormat'代替喬達的內置'DateTimeFormatter'? –
我是joda的新手,不知道如何使用它。 – zjuventus14