下个月的第一天与java Joda-Time

2022-09-01 01:22:47

您将如何重写下面的方法,该方法在下个月的第一天返回,并在Joda-Time中使用包?org.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;
}

答案 1
   LocalDate today = new LocalDate();
   LocalDate d1 = today.plusMonths(1).withDayOfMonth(1);

更简单一点,更干净一点,不是吗?:-)

更新:如果要返回日期:

return new Date(d1.toDateTimeAtStartOfDay().getMillis());

但我强烈建议您避免将纯DATE类型(即日历中的某一天,没有时间信息)与DATETIME类型混合,特别是与“物理”日期时间类型混合,因为很可怕。这有点像从整数类型转换为整数类型和浮点类型,您必须小心。java.util.Date


答案 2

我假设你想返回一个Date对象,所以:

public static Date firstDayOfNextMonth() {
    MutableDateTime mdt = new MutableDateTime();
    mdt.addMonths(1);
    mdt.setDayOfMonth(1);
    mdt.setMillisOfDay(0); // if you want to make sure you're at midnight
    return mdt.toDate();
}

推荐