当试图获取下个月的最后日期时,获取明年的下个月的最后日期

时间:2019-11-13 08:34:33

标签: java datetime java-date

尝试运行此代码,直到OCT都运行良好,但是在NOV中,就像 firstdate 2019-12-01 & lastdate 2020-12-31

public class Test1 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();         
        calendar.add(Calendar.MONTH, 1);
        String date;    
        calendar.set(Calendar.DATE,calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date nextMonthFirstDay = calendar.getTime();
        date=new SimpleDateFormat("YYYY-MM-dd").format(nextMonthFirstDay).toLowerCase();
        System.out.println("firstdate "+ date);

        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date nextMonthLastDay = calendar.getTime();
        date=new SimpleDateFormat("YYYY-MM-dd").format(nextMonthLastDay).toLowerCase();
        System.out.println("lastdate  "+date);

    }
}

我不知道为什么会这样显示。 是Java中的错误还是错误?

2 个答案:

答案 0 :(得分:6)

将日期格式更改为 yyyy-MM-dd (注意年份的小写字母)

它们都代表一年,但 yyyy 代表日历年,而 YYYY 代表星期。

类似...

date=new SimpleDateFormat("yyyy-MM-dd").format(nextMonthLastDay).toLowerCase();

希望有帮助!

答案 1 :(得分:1)

您似乎已经找到了可行的答案,但是,这是一个使用现代日期时间API java.time的答案,并且有点比计算方式更易读基于今天的下个月的第一天和最后一天:

public static void main(String[] args) {
    // base is today
    LocalDate today = LocalDate.now();
    /*
     * create a LocalDate from 
     * - the year of next month (may be different)
     * - the current month plus 1 and 
     * - the first day
     * ——> first day of next month
     */
    LocalDate firstDayOfNextMonth = LocalDate.of(
            today.plusMonths(1).getYear(),
            today.getMonth().plus(1),
            1);
    /*
     * create a LocalDate from 
     * - the first day of next month (just created above)
     * - add a month and
     * - subtract one day
     * ——> last day of next month
     */
    LocalDate lastDayOfNextMonth = firstDayOfNextMonth.plusMonths(1).minusDays(1);

    // print the results
    System.out.println("first date of upcoming month:\t"
                        + firstDayOfNextMonth.format(DateTimeFormatter.ISO_DATE));
    System.out.println("last date of upcoming month:\t"
                        + lastDayOfNextMonth.format(DateTimeFormatter.ISO_DATE));
}

不要被格式所误导,代码行明显更少,其输出是

first date of upcoming month:   2019-12-01
last date of upcoming month:    2019-12-31