public class DateUtils {
static final SimpleDateFormat DATE_SECOND_24H = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
static final SimpleDateFormat DATE_SECOND_12H = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
static final SimpleDateFormat DATE_DAY = new SimpleDateFormat( "yyyy-MM-dd" );
/**
* 获取当时时间字符串 yyyy-MM-dd HH:mm:ss
*/
public static String getSecStr(Date date){
return DATE_SECOND_24H.format(date);
}
/**
* 获取当时时间字符串 yyyy-MM-dd
*/
public static String getDayStr(Date date){
return DATE_DAY.format(date);
}
/**
* 获取当时时间 yyyy-MM-dd HH:mm:ss
*/
public static Date getBySec(String dateStr) throws ParseException {
return DATE_SECOND_24H.parse(dateStr);
}
/**
* 获取当时时间 yyyy-MM-dd
*/
public static Date getByDay(String dateStr) throws ParseException {
return DATE_DAY.parse(dateStr);
}
/**
* 获取当前时间到次日凌晨还有多少分钟
*/
public static Integer surplusMinute() {
return surplusTime(1);
}
/**
* 获取当前时间到次日凌晨还有多少分钟
*/
public static Integer surplusSecond() {
return surplusTime(2);
}
/**
* 获取当前时间到次日凌晨还有多少时间
* @param type 1=分钟 2=秒
*/
private static Integer surplusTime(Integer type) {
Calendar c = Calendar.getInstance();
c.setTime(new Date());
int hour = 23 - c.get(Calendar.HOUR_OF_DAY);
int minute = 60 - c.get(Calendar.MINUTE);
int second = 60 - c.get(Calendar.SECOND);
if (type == 1) return hour*60 + minute;
if (type == 2) return hour*60*60 + minute*60 + second;
return 0;
}
/**
* 计算给定日期与今天的整天数之差
*/
public static Integer betweenDays(Date d1,Date d2) throws ParseException {
Date startDate = getByDay(getDayStr(d1));
Date endDate = getByDay(getDayStr(d2));
Long betweenDate = (endDate.getTime() - startDate.getTime())/(60*60*24*1000);
return betweenDate.intValue();
}
/**
* 得到几天前的时间
* @param d 起始时间
* @param day 往前推几天
*/
public static Date getDateBefore(Date d, int day){
return calcDate(d,day,"-");
}
/**
* 得到几天后的时间
* @param d 起始时间
* @param day 往后推几天
*/
public static Date getDateAfter(Date d,int day){
return calcDate(d,day,"+");
}
/**
* 计算时间
*/
private static Date calcDate(Date d,int day,String symbol){
if (d==null) d=new Date();
Calendar now =Calendar.getInstance();
now.setTime(d);
int i = 0;
switch (symbol){
case "+": i=now.get(Calendar.DATE) + day;break;
case "-": i=now.get(Calendar.DATE) - day;break;
default: break;
}
now.set(Calendar.DATE,i);
return now.getTime();
}
/**
* 获取给定时间的任意时刻
*/
public static Date dayAnyTime(Date d,Integer hout,Integer minute,Integer second){
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.HOUR_OF_DAY, hout);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
return calendar.getTime();
}
}
日期工具类
最新推荐文章于 2024-10-06 20:16:20 发布