問題描述
你會如何用 org.joda.time 包重寫下面的方法,它返回下個月的第一天/joda-time/" rel="noreferrer">Joda-Time?
How would you rewrite the method below, which returns the first day of next month, with the org.joda.time
package in Joda-Time?
public static Date firstDayOfNextMonth() {
Calendar nowCal = Calendar.getInstance();
int month = nowCal.get(Calendar.MONTH) + 1;
int year = nowCal.get(Calendar.YEAR);
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date dueDate = new Date(cal.getTimeInMillis());
return dueDate;
}
推薦答案
LocalDate today = new LocalDate();
LocalDate d1 = today.plusMonths(1).withDayOfMonth(1);
更容易和更清潔,不是嗎?:-)
A little easier and cleaner, isn't it? :-)
更新:如果你想返回一個日期:
Update: If you want to return a date:
return new Date(d1.toDateTimeAtStartOfDay().getMillis());
但我強烈建議您避免將純 DATE 類型(即日歷中的一天,沒有時間信息)與 DATETIME 類型混合,特別是與可怕的 java.util.Date 一樣的物理"日期時間類型代碼> .這有點像從整數和浮點類型轉換,你必須小心.
but I strongly advise you to avoid mixing pure DATE types (i.e. a day in the calendar, without time information) with DATETIME types, specially with a "physical" datetime type as is the hideous java.util.Date
. It's somewhat like converting from-to integer and floating types, you must be careful.
這篇關于下個月的第一天使用 java Joda-Time的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!