Java获取下个月的第一天给出日期

时间:2017-03-24 12:23:43

标签: java date calendar

我正在尝试做一些非常简单的事情,拿一个日期并从下一个月的第一天开始。我尝试过使用日历。这里的日期是日历类型。

Calendar nextMonthFirst = (Calendar)date.clone();

     int year = date.get(Calendar.YEAR);
     int month =  date.get(Calendar.MONTH);

     nextMonthFirst.clear();

     nextMonthFirst.set(year, month+1,1);
     nextMonthFirst.add(Calendar.DAY_OF_MONTH, 0);
     return nextMonthFirst 

当我使用日期时       cal.set(2016,11,30); 我得到的输出为2017-01-01而不是2016-12-01。知道我做错了什么吗?

1 个答案:

答案 0 :(得分:3)

尝试以下操作,但请改用Java 8和java.time API!

import java.util.Calendar;

import static java.util.Calendar.*;
import static java.util.Calendar.DAY_OF_MONTH;

/**
 * Created by kedar on 3/24/17.
 */
public class FirstDayOfNext {
    public static void main(String[] args) {
        Calendar today = getInstance();
        today.clear();
        today.set(2016, NOVEMBER, 30);
        System.out.println("today date: " + today.getTime());
        Calendar next = getInstance();
        next.clear();
        next.set(YEAR, today.get(YEAR));
        next.set(MONTH, today.get(MONTH) + 1);
        next.set(DAY_OF_MONTH, 1); // optional, default: 1, our need
        System.out.println("next  date: " + next.getTime());
    }
}

打印:

today date: Wed Nov 30 00:00:00 PST 2016
next  date: Thu Dec 01 00:00:00 PST 2016

正如所料。