做财务系统经常会用到会计期间的计算,总结了一些!
/**
* 得到某年某月的第一天
*
* @param year
* @param month
* @return
*/
public static String getFirstDayOfMonth(Integer year, Integer month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month-1);
cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
/**
* 返回指定年月的最后一天
*
* @param year
* @param month
* @return
*/
public static Date getLastDayOfMonth(Integer year, Integer month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month,-1);
calendar.roll(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
<pre name="code" class="java"> <pre name="code" class="java"> /**
* 返回指定年月的最后一天
*
* @param year
* @param month
* @return
*/
public static String getLastDayOfMonth(int year,int month)
{
Calendar cal = Calendar.getInstance();
//设置年份
cal.set(Calendar.YEAR,year);
//设置月份
cal.set(Calendar.MONTH, month-1);
//获取某月最大天数
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//设置日历中月份的最大天数
cal.set(Calendar.DAY_OF_MONTH, lastDay);
//格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String lastDayOfMonth = sdf.format(cal.getTime());
return lastDayOfMonth;
}
/**
* 比较两个日期之间的大小
*
* @param d1
* @param d2
* @return 前者大于后者返回true 反之false
*/
public static boolean compareDate(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
int result = c1.compareTo(c2);
if (result >= 0)
return true;
else
return false;
}
public static String getFirstDate(){ //第一天的日期
Calendar ca = Calendar.getInstance();
ca.setTime(new Date()); // someDate 为你要获取的那个月的时间
ca.set(Calendar.DAY_OF_MONTH, 1);
Date firstDate = ca.getTime();
return getDateFormat(firstDate);
}
public static String getDateFormat(Date date) {
//Date now = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
return sf.format(date);
}
public static String getTimeFormat(Date date) {//带有时分秒的日期格式
//Date now = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sf.format(date);
}
public static Date StringToDate(String str){//字符串转换为日期格式
if(str==null||str.trim().equals("")) return null;
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
date = sf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
date = null;
}
return date;
}