2014-05-23 46 views
0

我從來沒有使用Joda-Time之前,但我有ArrayList包含LocalDate和計數的對象。所以我在ArrayList中每天都有計數,每天只有一次在ArrayList中。 我需要計算每個月的年份,這是列表中的計數。爪哇喬達時間,分配LocalDate月份和年份

我的數據: 如:

dd.MM.yyyy 
17.01.1996 (count 2) 
18.01.1996 (count 3) 
19.02.1996 (count 4) 
19.03.1996 (count 1) 
18.05.1997 (count 3) 

現在我想outpur這樣的:

MM.yyyy 
01.1996 -> 2 (17.1.1996) + 3 (18.1.1996) = 5 
02.1996 -> 4 (19.2.1996)     = 4 
03.1996 -> 1 (19.3.1996)     = 1 
05.1997 -> 3 (18.5.1997)     = 3 

只要我需要得到計數每一個月,但我不知道什麼是最好的實現這一目標的方法。

數據類:

private class Info{ 
    int count; 
    LocalDate day; 
} 

,並導致我會把一些類,其中包含月份和年份日期+計數。

回答

5

Joda-Time中,有一類代表年份+月份信息,名稱爲YearMonth

你需要做的主要是構建一個Map<YearMonth, int>存儲每個YearMonth的計數,通過其中包含LocalDate和算你原來的List循環,並相應地更新地圖。從LocalDateYearMonth

轉換應該是直截了當:YearMonth yearMonth = new YearMonth(someLocalDate);應該工作

在僞代碼,它看起來像:

List<Info> dateCounts = ...; 
Map<YearMonth, Integer> monthCounts = new TreeMap<>(); 

for (Info info : dateCounts) { 
    YearMonth yearMonth = new YearMonth(info.getLocalDate()); 
    if (monthCounts does not contains yearMonth) { 
     monthCounts.put(yearMonth, info.count); 
    } else { 
     oldCount = monthCounts.get(yearMonth); 
     monthCounts.put(yearMonth, info.count + oldCount); 
    } 
} 

// feel free to output content of monthCounts now. 
// And, with TreeMap, the content of monthCounts are sorted 
+0

謝謝,它的工作像它應該。你在psuedocode new YearCount(info.getLocalDate())中犯了一個小錯誤;應該是新的YearMonth(info.getLocalDate()); ,但很容易弄清楚。 – user3658759

+0

@ user3658759 lol我不知道爲什麼我在那裏寫了那個奇怪的類名。現在修復 –

0

您正在尋找位於Joda-Time 2.3的LocalDate班級的getMonthOfYeargetYear方法。

for (Info info : infos) { 
    int year = info.day.getYear(); 
    int month = info.day.getMonthOfYear(); 
} 

從那裏寫代碼以任何適合您的方式累計計數。您可以保留一個年份的地圖,作爲導致月份地圖的關鍵字。您可以創建一個格式爲「YYYY-MM」的字符串作爲映射的關鍵字。