Java获取指定日期,本月第一天、最后一天,上月第一天、最后一天、获得指定日期的前几天、获得指定日期的所在周
@Component
public class DateUtils {
/**
* 获取本月第一天
* @return
*/
public static String getMinDate(){
//获取当前月第一天
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
//设置为1号,当前日期既为本月第一天
c.set(Calendar.DAY_OF_MONTH,1);
String first = format.format(c.getTime());
return first;
}
/**
* 获取本月最后一天
* @return
*/
public static String getMaxDate(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String lastDay = format.format(ca.getTime());
return lastDay;
}
/**
* 获取上月第一天
* @return
*/
public static String getPrecedingMonthMinDate(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal_1=Calendar.getInstance();
cal_1.add(Calendar.MONTH, -1);
cal_1.set(Calendar.DAY_OF_MONTH,1);
return format.format(cal_1.getTime());
}
/**
* 获取上月最后一天
* @return
*/
public static String getPrecedingMonthMaxDate(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar cale = Calendar.getInstance();
cale.set(Calendar.DAY_OF_MONTH,0);
String lastDay = format.format(cale.getTime());
return lastDay;
}
/**
* 获取昨天
* @return
*/
public static String getYesterdayDate(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar cale = Calendar.getInstance();
cale.setTime(new Date());
cale.add(Calendar.DATE,-1);
String yesterday = format.format(cale.getTime());
return yesterday;
}
/**
* 获取今天
* @return
*/
public static String getTodayDate(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar cale = Calendar.getInstance();
cale.setTime(new Date());
cale.add(Calendar.DATE,0);
String today = format.format(cale.getTime());
return today;
}
/**
* 获得指定日期的前几天
* @param specifiedDay
* @return
* @throws Exception
*/
public static String getSpecifiedDayBefore(String specifiedDay,Integer severalDays){
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day - severalDays);
String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
return dayBefore;
}
/**
* 获得指定日期的所在周
* @param day
* @return
* @throws Exception
*/
public static Integer getWeekOfYear(String day){
Calendar c = Calendar.getInstance();
Date date= null;
try {
date = new SimpleDateFormat("yy-MM-dd").parse(day);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int index = c.get(Calendar.WEEK_OF_YEAR);
return index;
}
}