I am writing a program to calculate age difference in java using Joda Time, and when calculating hoursBetween(), it does not take into account AM and PM. Here's my code:
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();
}
}}
If my input for date of birth is "01/01/2014 12:00 AM" and my input for the current time is "01/01/2014 12:00 PM" the result is: "You are 0 years, 0 months, 0 hours, and 0 minutes old." When it should be 12 hours old. Is there a way to fix this? My guess is there is some way to implement the halfdayOfDay() method and invoke it on my DateTime's, but I haven't found it...Thanks for any help!(By the way, I am using 12 hour day's for input, but while parsing it still accepts 13:00, when it should max out at 12:00!)