1.使用calendar取上月最后一天
使用calendar.getActualMaximum(Calendar.DAY_OF_MONTH)取最大值
class="java" name="code">
package com.andrew.code;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* CalendarUtil
*
* @author andrew
* @date 2018/4/17.
*/
public class CalendarUtil {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("the last day of last month:" + sdf.format(getLastDayOfLastMonth()));
}
/**
* the last day of last month
*/
public static Date getLastDayOfLastMonth() {
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
return calendar.getTime();
}
}
2.使用calendar取当月第一天
使用calendar.set(Calendar.DAY_OF_MONTH, 1);设置最小值
package com.andrew.code;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* CalendarUtil
*
* @author andrew
* @date 2018/4/17.
*/
public class CalendarUtil {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("the first day of this month:" + sdf.format(getFirstDayOfThisMonth()));
}
/**
* the first day of this month
*/
public static Date getFirstDayOfThisMonth() {
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
}
补充说明
(1) 注意calender的变量
MONTH,DAY_OF_MONTH,HOUR_OF_DAY,MINUTE,SECOND
(2) 取最大值,最小值
calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
calendar.set(Calendar.MINUTE, 0);