继上一篇文件操作工具类,奉上时间操作工具类
/**
* 常用日期操作方法
*/
public class DateUtil {
protected static final Log log = LogFactory.getLog(DateUtil.class);
public static final String YEAR_STR="年";
public static final String MONTH_STR="月";
public static int diffDayCount(Calendar start, Calendar end) {
int result = 0;
DayDate startDay = new DayDate(start);
DayDate endDay = new DayDate(end);
if (startDay.equals(endDay)
|| startDay.equals(startDay.getLastDay(endDay))) {
return result;
}
if (startDay.getYear() == endDay.getYear()) {
return endDay.getDayOfY() - startDay.getDayOfY();
} else {
Calendar tmp = Calendar.getInstance();
result = startDay.getCalendar().getActualMaximum(
Calendar.DAY_OF_YEAR)
- startDay.getDayOfY();
for (int i = startDay.getYear() + 1; i < endDay.getYear(); i++) {
tmp.set(i, tmp.get(Calendar.MONTH), tmp
.get(Calendar.DAY_OF_MONTH));
result += tmp.getActualMaximum(Calendar.DAY_OF_YEAR);
}
result += endDay.getDayOfY();
}
return result;
}
public static int getYearInt() {
String year = format(new Date(),"yyyy");
return Integer.parseInt(year);
}
/**
* 计算传入日期所在月份的最后一天
*/
public static Date lastDayOfSameMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.roll(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
/**
* 计算两个日期间隔天数
*/
public static long getNumBetweenTwoDate(Date beginDate,Date endDate){
long dif = endDate.getTime() - beginDate.getTime();
return dif/(1000*60*60*24);
}
/**
* 日期转换 ****年**月
* @return
*/
public static String DateTransfer(Date date){
String year = format(date,"yyyy");
String month = format(date,"MM");
return year+YEAR_STR+month+MONTH_STR;
}
/**
* 拆分给定字符串构造本月月初 格式为:2009-08-01
*/
public static String giveMonthFist(String strdate) {
// 以“-”为分隔符拆分字符串
String strArray[] = strdate.split("-");
String tempyear = strArray[0]; // 得到字符串中的年
String tempmonth = strArray[1]; // 得到字符串中的月
// 拼接成月首字符串
return tempyear + "-" + tempmonth + "-01";
}
/**
* 拆分给定字符串构造本月月末 格式为:2009-08-01
*/
public static String giveMonthLast(String strdate) {
// 先得到下个月的同一天
String addmonth = DateUtil.addMonth(strdate);
// 得到下个月的月初
String monthfirst = DateUtil.giveMonthFist(addmonth);
// 下个月月初减一天为本月月末
String subday = DateUtil.subDay(monthfirst);
return subday;
}
/**
* 给定的日期减一个月 格式为:2009-08-01
*/
public static String subMonth(String strdate) {
Date date = new Date(); // 构造一个日期型中间变量
String dateresult = null; // 返回的日期字符串
// 创建格式化格式
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// 加减日期所用
GregorianCalendar gc = new GregorianCalendar();
try {
date = df.parse(strdate); // 将字符串格式化为日期型
} catch (ParseException e) {
e.printStackTrace();
}
gc.setTime(date); // 得到gc格式的时间
gc.add(2, -1); // 2表示月的加减,年代表1依次类推(周,天。。)
// 把运算完的时间从新赋进对象
gc.set(gc.get(gc.YEAR), gc.get(gc.MONTH), gc.get(gc.DATE));
// 在格式化回字符串时间
dateresult = df.format(gc.getTime());
return dateresult;
}
/**
* 给定的日期加一个月 格式为:2009-08-01
*/
public static String addMonth(String strdate) {
Date date = new Date(); // 构造一个日期型中间变量
String dateresult = null; // 返回的日期字符串
// 创建格式化格式
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// 加减日期所用
GregorianCalendar gc = new GregorianCalendar();
try {
date = df.parse(strdate); // 将字符串格式化为日期型
} catch (ParseException e) {
e.printStackTrace();
}
gc.setTime(date); // 得到gc格式的时间
gc.add(2, 1); // 2表示月的加减,年代表1依次类推(周,天。。)
// 把运算完的时间从新赋进对象
gc.set(gc.get(gc.YEAR), gc.get(gc.MONTH), gc.get(gc.DATE));
// 在格式化回字符串时间
dateresult = df.format(gc.getTime());
return dateresult;
}
/**
* 给定的日期减一天 格式为:2009-08-01
*/
public static String subDay(String strdate) {
Date date = new Date(); // 构造一个日期型中间变量
String dateresult = null; // 返回的日期字符串
// 创建格式化格式
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// 加减日期所用
GregorianCalendar gc = new GregorianCalendar();
try {
date = df.parse(strdate); // 将字符串格式化为日期型
} catch (ParseException e) {
e.printStackTrace();
}
gc.setTime(date); // 得到gc格式的时间
gc.add(5, -1); // 2表示月的加减,年代表1依次类推(3周....5天。。)
// 把运算完的时间从新赋进对象
gc.set(gc.get(gc.YEAR), gc.get(gc.MONTH), gc.get(gc.DATE));
// 在格式化回字符串时间
dateresult = df.format(gc.getTime());
return dateresult;
}
/**
* 给定的日期加一天 格式为:2009-08-01
*/
public static String addDay(String strdate) {
Date date = new Date(); // 构造一个日期型中间变量
String dateresult = null; // 返回的日期字符串
// 创建格式化格式
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// 加减日期所用
GregorianCalendar gc = new GregorianCalendar();
try {
date = df.parse(strdate); // 将字符串格式化为日期型
} catch (ParseException e) {
e.printStackTrace();
}
gc.setTime(date); // 得到gc格式的时间
gc.add(5, 1); // 2表示月的加减,年代表1依次类推(3周....5天。。)
// 把运算完的时间从新赋进对象
gc.set(gc.get(gc.YEAR), gc.get(gc.MONTH), gc.get(gc.DATE));
// 在格式化回字符串时间
dateresult = df.format(gc.getTime());
return dateresult;
}
/**
* 给定的日期加若干天 格式为:2009-08-01
*/
public static String addSomeDay(String strdate,int days) {
Date date = new Date(); // 构造一个日期型中间变量
String dateresult = null; // 返回的日期字符串
// 创建格式化格式
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// 加减日期所用
GregorianCalendar gc = new GregorianCalendar();
try {
date = df.parse(strdate); // 将字符串格式化为日期型
} catch (ParseException e) {
e.printStackTrace();
}
gc.setTime(date); // 得到gc格式的时间
gc.add(5, days); // 2表示月的加减,年代表1依次类推(3周....5天。。)
// 把运算完的时间从新赋进对象
gc.set(gc.get(gc.YEAR), gc.get(gc.MONTH), gc.get(gc.DATE));
// 在格式化回字符串时间
dateresult = df.format(gc.getTime());
return dateresult;
}
/**
* 给定的两个日期作比较,返回bool的类型 格式为:2009-08-01
*
* @throws ParseException
*/
public static boolean boolcompara(String startdate, String enddate) throws ParseException {
if (DateFormat.getDateInstance().parse(startdate).compareTo(DateFormat.getDateInstance().parse(startdate)) >= 0) {
return true;
} else {
return false;
}
}
/**
* 日期date转换为String格式
* 日期格式为yyyy-MM-dd
* @param dateValue
* @return
*/
public static String format(Date date, String newFormat){
if ((date == null) || (newFormat == null)) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat(newFormat);
return formatter.format(date);
}
/**
* 获得指定日期的前一天
*
* @param specifiedDay
* @return
* @throws Exception
* @throws Exception
*/
public static String getSpecifiedDayBefore(String specifiedDay) throws Exception {
String dayBefore = getSpecifiedDayBefore(specifiedDay, 1);
return dayBefore;
}
/**
* 获得指定日期的前几天
*
* @param specifiedDay
* @return
* @throws Exception
* @throws Exception
*/
public static String getSpecifiedDayBefore(String specifiedDay, int days) throws Exception {
Calendar c = Calendar.getInstance();
Date date = null;
String dayBefore = "";
try {
date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day - days);
dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
} catch (ParseException e) {
throw new Exception("日期转化错误");
}
return dayBefore;
}
/**
* string to date
*
* @param date
* @return Date
*/
public static Date parseDate(String date) {
String patterns[] = { "yyyy-MM-dd", "yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss.S",
"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.S" };
try {
return org.apache.commons.lang.time.DateUtils.parseDate(date,
patterns);
} catch (ParseException e) {
log.error(e);
}
return null;
}
public static String parseDate(String date ,int length) {
if(StringUtil.isNotNull(date)) {
return DateUtil.toString(DateUtil.parseDate(date), length);
}
return null;
}
public static String toString(Date date, int length) {
SimpleDateFormat formatter = null;
if (length == 10)
formatter = new SimpleDateFormat("yyyy-MM-dd");
else if (length == 19)
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
else if (length == 7)
formatter = new SimpleDateFormat("yyyy-MM");
else if (length == 21)
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
else
return date.toString();
return formatter.format(date);
}
public static String toStringNoInterval(Date date, int length) {
SimpleDateFormat formatter = null;
if (length == 8)
formatter = new SimpleDateFormat("yyyyMMdd");
else if (length == 6)
formatter = new SimpleDateFormat("yyyyMM");
else if (length == 14)
formatter = new SimpleDateFormat("yyyyMMddHHmmss");
else
return date.toString();
return formatter.format(date);
}
public static int getYear(java.util.Date date) {
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.YEAR);
}
public static int getMonth(java.util.Date date) {
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.MONTH) + 1;
}
public static int getDay(java.util.Date date) {
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.DAY_OF_MONTH);
}
public static int getHour(java.util.Date date) {
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.HOUR_OF_DAY);
}
/**
* 取得当前日期格式为:2010-05-08
*
* @return String
*/
public static String getCurrentDate() {
// Format the current time.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 取得当前日期格式为:2010-05-08 13:33:16
* @return
*/
public static String getCurrentDateByAll() {
// Format the current time.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 日期string转换为date格式
* 日期格式为yyyy-MM-dd hh:mm:ss
* @param dateValue
* @return
*/
public static Date getDateTranferValueByAll(String dateValue) {
java.util.Date date = null;
if (!StringUtil.isEmpty(dateValue)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = sdf.parse(dateValue);
} catch (ParseException e) {
e.printStackTrace();
}
}
return date;
}
/**
* 日期string转换为date格式
* 日期格式为yyyy-MM-dd
* @param dateValue
* @return
*/
public static Date getDateTranferValue(String dateValue) {
java.util.Date date = null;
if (!StringUtil.isEmpty(dateValue)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = sdf.parse(dateValue);
} catch (ParseException e) {
e.printStackTrace();
}
}
return date;
}
/**
* 比较两个日期大小。
* @param DATE1
* @param DATE2
* @return 前者大于等于后者返回1,前者小返回2,异常返回-1.
*/
public static int compareDate(String DATE1, String DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() >= dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return 2;
} else{
return -1;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return -1;
}
/**
* Desc:yyyy-MM-DD日期比较
* @date 2013-5-9 下午02:31:03
* @param DATE1
* @param DATE2
* @return 前者>后者返回true,否则前者<=后者返回false
*/
public static boolean compareTo(Date DATE1, Date DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
// DATE1>DATE2 返1, DATE2>DATE1 返-1, DATE1=DATE2 返0
DATE1 = df.parse(DateUtil.toString(DATE1, 10));
int val = DATE1.compareTo(DATE2);
if(val > 0){
return true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return false;
}
/**
* 得到当前日期的一周前的日期yyyy-MM-dd
* @return
*/
public static String getLastWeek()
{
Date currDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(currDate);
calendar.add(Calendar.DATE, -7);
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/**
* 得到当前日期的N个月前的日期
* @return
*/
public static String getBeforeMonth(int number)
{
Date currDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(currDate);
calendar.add(Calendar.MONTH, -number);
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/**
* 获得num年前的连接几年
* 2012-11-06
* @param num
* @return
*/
public static Map getBackComYearSelect(int num){
//年度选择框构成
Map map1 = new LinkedHashMap<String, String>();
Date date = new Date();
//获得当前的年份
int year = date.getYear()+ 1900;
for(int i = 0;i<num; i++){
map1.put(year, year);
year = year - 1;
}
return map1;
}
public synchronized static String buildFileName() {
return System.currentTimeMillis() + ".html";
}
/**
* 得到当前日期的N年前的年份
* @return
*/
public static String getBeforeYear(int number)
{
Date currDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(currDate);
calendar.add(Calendar.YEAR, -number);
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
return sdf.format(date);
}
/**
* 将日期字符串转成需要的格式
* @param timeString
* @param pattern
* @param format
* @return
*/
public static String pareTimeString(String timeString, String pattern, String format) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
SimpleDateFormat sdf = new SimpleDateFormat(format);
if(timeString == null)
return "";
try {
Date date = df.parse(timeString);
return sdf.format(date);
} catch (Exception e) {
e.printStackTrace();
return timeString;
}
}
/**
* 是否为一个合法的日期格式
* @param inDate
* @return
*/
public static String isValidDate(String value) {
if (value == null) {
return "";
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
if (value.trim().length() != 21) {
return value;
}
dateFormat.setLenient(false);
try {
dateFormat.parse(value.trim());
} catch (ParseException pe) {
return value;
}
return value.substring(0, 10);
}
}