2010-03-22 57 views
1

我使用以下截圖查找Joda中幾個時間段的開始和結束。我左肩上的小惡魔說這是要走的路......但我不相信他。查找開始和結束的年/月/日/小時

有沒有人有一些joda的經驗做一個簡要的檢查,並告訴我,這個小傢伙是正確的?

(將僅用於UTC datetime對象)

謝謝!

/* Year */ 
private static DateTime endOfYear(DateTime dateTime) { 
    return endOfDay(dateTime).withMonthOfYear(12).withDayOfMonth(31); 
} 

private static DateTime beginningOfYear(DateTime dateTime) { 
    return beginningOfMonth(dateTime).withMonthOfYear(1); 
} 

/* Month */ 
private static DateTime endOfMonth(DateTime dateTime) { 
    return endOfDay(dateTime).withDayOfMonth(dateTime.dayOfMonth().getMaximumValue()); 
} 

private static DateTime beginningOfMonth(DateTime dateTime) { 
    return beginningOfday(dateTime).withDayOfMonth(1); 
} 

/* Day */ 
private static DateTime endOfDay(DateTime dateTime) { 
    return endOfHour(dateTime).withHourOfDay(23); 
} 

private static DateTime beginningOfday(DateTime dateTime) { 
    return beginningOfHour(dateTime).withHourOfDay(0); 
} 

/* Hour */ 
private static DateTime beginningOfHour(DateTime dateTime) { 
    return dateTime.withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0); 
} 

private static DateTime endOfHour(DateTime dateTime) { 
    return dateTime.withMillisOfSecond(999).withSecondOfMinute(59).withMinuteOfHour(59); 
} 
+2

你有沒有試過編寫jUnit測試? – 2010-03-22 17:27:24

+0

我正在尋找比這更簡單的方式,它對我來說看起來有點尷尬。但它的作品,即使在一些角落的情況下。 – reto 2010-03-22 17:42:18

+1

我認爲你需要扭轉endOfYear的操作。它看起來像2/2/10會給你一個12/28/10的日期。從XP/TDD的角度來看,你是否需要所有這些開始/結束方法?如果您只需要一年和一年的開始和結束時間,那就實現這一點。如果您以後發現需要日日時間,可以添加它們。最有可能的是,你不會全部需要它們。而較少的代碼意味着缺少隱藏的地方。 – 2010-03-22 18:12:10

回答

1

喬達確實能夠提供DateMidnight和LOCALDATE的可能緩解不必處理小時和分鐘你在哪裏真的只在乎時間界限的情況下,這麼多。 LocalDate還實現了ReadablePartial接口,可能需要考慮反映感興趣的領域的其他實現。

+0

不贊成與午夜有關的類和方法在喬達時間。替換爲['withTimeAtStartOfDay'](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#withTimeAtStartOfDay--)方法。 – 2016-10-19 01:38:45

0

我知道java庫是基於0(即1月是0,12月是11)。我不認爲喬達是,但如果你不確定雙重檢查。

+0

不,Joda-Time(和java.time)在1月至12月使用1-12的健全序數。 – 2016-10-19 01:37:25

相關問題