常用的时间工具
public class DateUnits {
//获取本地时间并转换为"yyyy-MM-dd HH:mm:ss"格式
public static String getDateTime1() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return sdf.format(d);
}
//获取本地时间并转换为"yyyyMMddHHmmss"格式
public static String getDateTime2() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return sdf.format(d);
}
//获取本地时间并转换为"yyyyMMdd"格式,只返回年月日
public static String getDate() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return sdf.format(d);
}
//将时间类型转换为"yyyy-MM-dd HH:mm:ss"字符串格式
public static String date2Str1(Date d) {
//例如:
//数据库中获取到的时间格式:Fri Jul 10 19:19:41 CST 2020
//转换后的格式:2020-07-10 19:19:41
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return sdf.format(d);
}
//将"yyyy-MM-dd HH:mm:ss"格式的时间字符串转换为Date格式
public static Date date2Str2(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.parse(date);
}
//比较两个日期相差的小时
public static Integer dimDD(Date date1, Date date2) {
long l = 0L;
long d1 = date1.getTime();
long d2 = date2.getTime();
if (d1 > d2)
l = d1 - d2;
else
l = d2 - d1;
return (int) l % (1000 * 24 * 60 * 60) / (1000 * 60 * 60);
}
//判断当前时间是否为00分或30分
public static boolean isHalfHour(){
Date d = new Date();
//格式化时间串,HH:MM:SS分别是时分秒,这里只判断分钟,有mm就够了
//需要秒的话,就mm:ss,下面就判断是否 00:00
SimpleDateFormat sdf = new SimpleDateFormat("mm");
String timeStr=sdf.format(d);
//判断是否为需要的时间
if (timeStr.equals("00") || timeStr.equals("30"))
return true;
else
return false;
}
//将Date格式转换为"HH:mm",只保留小时和分钟
public static String formatHM(Date d){
//格式化时间串,HH:MM:SS分别是时分秒,这里只判断分钟,有mm就够了
//需要秒的话,就mm:ss,下面就判断是否 00:00
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String timeStr=sdf.format(d);
return timeStr;
}
}