2014-01-22 24 views
-2

我正在編寫一個程序來計算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!)

+0

爲什麼要用'SimpleDateFormat'代替喬達的內置'DateTimeFormatter'? –

+0

我是joda的新手,不知道如何使用它。 – zjuventus14

回答

0

你的小時數做

Hours.hoursBetween(dob1, now1).getHours() % 12 

所以

之間的模數12
12 % 12 = 0 
+0

那麼我該如何解決這個問題? – zjuventus14

+0

@ user2756173你想用模數來做什麼? –

+0

謝謝,我使用它,以便它在幾個月和幾年(例如1年,12個月)之間不會重複!沒有意識到這是如何影響程序 – zjuventus14

0

你正在努力工作。

Joda-Time提供了完成這項工作的課程:PeriodFormatterPeriodFormatterBuilder

請參閱this answer by BalusC

這個答案顯示了這樣的代碼:

PeriodFormatter formatter = new PeriodFormatterBuilder() 
    .appendSeconds().appendSuffix(" seconds ago\n") 
    .appendMinutes().appendSuffix(" minutes ago\n") 
    .appendHours().appendSuffix(" hours ago\n") 
    .appendDays().appendSuffix(" days ago\n") 
    .appendWeeks().appendSuffix(" weeks ago\n") 
    .appendMonths().appendSuffix(" months ago\n") 
    .appendYears().appendSuffix(" years ago\n") 
    .printZeroNever() 
    .toFormatter();