这里写目录标题
时间工具类
获得当前时间 格式为 yyyy-MM-dd HH:mm:ss
/**
* 获得当前日期 yyyy-MM-dd HH:mm:ss
*/
public static String getCurrentTime() {
// 小写的hh取得12小时,大写的HH取的是24小时
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return df.format(date);
}
获取当前时间 格式为时间戳
/**
* 获取系统当前时间戳
*/
public static String getSystemTime() {
String current = String.valueOf(System.currentTimeMillis());
return current;
}
获取两个时间的差值 返回时间戳
两个参数类型yyyy-MM-dd HH:mm:ss
返回时间戳
/**
* 得到两个时间差 格式yyyy-MM-dd HH:mm:ss
*
* @param start 20xx-xx-xx xx:xx:xx
* @param end 21xx-xx-xx xx:xx:xx
* @return
*/
public static long dateSubtraction(String start, String end) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = df.parse(start);
Date date2 = df.parse(end);
return date2.getTime() - date1.getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
获取当前日期是一个星期的第几天
/**
* 获取当前日期是一个星期的第几天
*
* @return 2
*/
public static int getDayOfWeek() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
return cal.get(Calendar.DAY_OF_WEEK) - 1;
}
判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
/**
* 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
*
* @param nowTime 当前时间
* @param dateSection 时间区间 2018-01-08,2019-09-09
* @return
* @author jqlin
*/
public static boolean isEffectiveDate(Date nowTime, String dateSection) {
try {
String[] times = dateSection.split(",");
String format = "yyyy-MM-dd";
Date startTime = new SimpleDateFormat(format).parse(times[0]);
Date endTime = new SimpleDateFormat(format).parse(times[1]);
if (nowTime.getTime() == startTime.getTime()
|| nowTime.getTime() == endTime.getTime()) {
return true;
}
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(startTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if (isSameDay(date, begin) || isSameDay(date, end)) {
return true;
}
if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 != null && cal2 != null) {
return cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
} else {
throw new IllegalArgumentException("The date must not be null");
}
}
日期转时间戳
public static long getTimeByDate(String time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = format.parse(time);
//日期转时间戳(毫秒)
return date.getTime();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
时间戳转日期
Long timeStamp = System.currentTimeMillis(); //获取当前时间戳
System.out.println(timeStamp);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp)))); // 时间戳转换成时间
System.out.println("格式化结果:" + sd);