java 获取指定月份的第一天和最后一天

package com.guanlan.layout.txz.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
* Created by qwerthink on 2017/3/30.
*/
public class DateUtil {
private static SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM");
private static Calendar calendar=Calendar.getInstance();

/*
输入日期字符串比如201703,返回当月第一天的Date
*/
public static Date getMinDateMonth(String month){
try {
Date nowDate=sdf.parse(month);
calendar = Calendar.getInstance();
calendar.setTime(nowDate);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}

/*
输入日期字符串,返回当月最后一天的Date
*/
public static Date getMaxDateMonth(String month){
try {
Date nowDate=sdf.parse(month);
calendar = Calendar.getInstance();
calendar.setTime(nowDate);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}

public static void main(String[] args) throws ParseException{
String month="201705";
System.out.println(getMinDateMonth(month));
System.out.println(getMaxDateMonth(month));
}
}

posted @ 2017-04-24 16:47  qwerthink  阅读(4267)  评论(0编辑  收藏  举报