下个月的第一天用java Joda-Time [英] First day of next month with java Joda-Time
问题描述
如何重写以下方法,该方法返回下个月的第一天, org.joda.time /www.joda.org/joda-time/\"> 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!