import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 时间(日期)工具
* @author lyf
* @date 2015-06-23
* @version 0.1
*/
public class DateUtil {
Calendar calendar;
/**
* 获取currentDate时间的dayNum后(前)的时间
* @param currentDate 当前时间,"yyyy-MM-dd HH:mm:ss"
* @param dayNum 前(后)几天,负数代表前几天,整数代表后几天
* @return 改变后的时间("yyyy-MM-dd HH:mm:ss")
*/
public String getBeforeCurrentDate(String currentDate,int dayNum){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (calendar == null) {
calendar = Calendar.getInstance();
}
try {
Date curDate = formatter.parse(currentDate);
calendar.setTime(curDate);
calendar.add(Calendar.DAY_OF_MONTH, dayNum);
Date bDate = calendar.getTime();
String beforeDate = formatter.format(bDate);
return beforeDate;
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取currentDate时间的dayNum后(前)的时间
* @param currentDate 当前时间,格式自定义
* @param dayNum 前(后)几天,负数代表前几天,整数代表后几天
* @param DateFormat 时间格式
* @return 改变后的时间
*/
public String getBeforeCurrentDate(String currentDate,int dayNum,String DateFormat){
SimpleDateFormat formatter = new SimpleDateFormat(DateFormat);
if (calendar == null) {
calendar = Calendar.getInstance();
}
try {
Date curDate = formatter.parse(currentDate);
calendar.setTime(curDate);
calendar.add(Calendar.DAY_OF_MONTH, dayNum);
Date bDate = calendar.getTime();
String beforeDate = formatter.format(bDate);
return beforeDate;
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
/**
* 比较两个时间先后
* @param aTime 格式例如“2015-05-25 17:49:30”
* @param bTime 格式例如“2015-05-25 17:49:30”
* @return true: aTime在bTime后
*/
public static boolean compareTime(String aTime, String bTime) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date aDate = formatter.parse(aTime);
Date bDate = formatter.parse(bTime);
if (aDate.after(bDate)) {
return true;
}else {
return false;
}
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
/**
* 获得当天日期 默认格式为2014-12-05
*/
public String getCurrentDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(new Date());
}
/**
* 获得当天日期
* @param 格式为type----"yyyyMMddhhmmss"
*/
public String getCurrentDate(String type) {
SimpleDateFormat formatter = new SimpleDateFormat(type);
return formatter.format(new Date());
}
}
获取当前日期时间,前一天时间,后一天时间,时间日期对比前后
最新推荐文章于 2021-04-23 10:56:00 发布