在开发中有一些需求和Date和Calendar有关,所以在这里总结一下这些实现,以后可以直接使用:
1.获取指定日期是星期几, 参数为null时表示获取当前日期是星期几
public static String getWeekOfDate(Date date) {
String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar calendar = Calendar.getInstance();
if (date != null) {
calendar.setTime(date);
}
int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) {
w = 0;
}
return weekOfDays[w];
}
2.获取本月的第一天(或者当前日期)
public static String currDate(String current) {
String currdate = "";
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
if ("1".equals(current)) { //current=1:表示获取本月的第一天,否则获取当前日期
cal.set(Calendar.DAY_OF_MONTH, 1);
}
currdate = new SimpleDateFormat("yyyy-MM").format(cal.getTime());
return currdate;
}
3.查询上个月(上上个月。。。)的第一天和最后一天
public static String findLastMonth(int num) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
Calendar cal = Calendar.getInstance();
GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, num); //-1:表示上个月 -2:表示上上个月
Date theDate = calendar.getTime();
gcLast.setTime(theDate);
gcLast.set(Calendar.DAY_OF_MONTH, 1);
String day_first_prevM = df.format(gcLast.getTime());
StringBuffer str = new StringBuffer().append(day_first_prevM);
day_first_prevM = str.toString();
return day_first_prevM;
}
4.查询当前日期前(后)x天的日期
public static String beforNumberDay(Date date, int day) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_YEAR, day);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
5.获取某年度的最后一天
public static String getYearLastDate(int year, String pattern) {
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.roll(Calendar.DAY_OF_YEAR, -1);
Date currYearLast = calendar.getTime();
return DateFormatUtils.format(currYearLast, pattern);
}