我正在尝试使用以下代码,但返回的是错误的月份。

Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);
cal.set(Calendar.DAY_OF_MONTH, 0);
return cal.getTime();

最佳答案

获取该月的天数:


Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
int noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

将日历设置为本月的最后一天:

Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

关于java - 给定一个日期对象,我该如何确定该月的最后一天?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/72381/

10-13 22:42