版权声明:天际流火叩响大地之门,岁月星辰刻画沧桑年轮! https://blog.csdn.net/ytfunnysite/article/details/83058143
很久没写日期时间差的东西,刚好用到,备份个工具类,包含日期date的格式化操作,计算两个日期的时间差,可以自由精确到小时,分钟,秒的量级,也可计算一个date的时间距离当前时间的时间差等等。
指定格式的日期字符串转Date
Date endDate= null ;
try {
endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(“日期的string字符串”);
} catch (ParseException e) {
e.printStackTrace();
}
计算两个date的时间差
package com.thesis.mentor.base;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Administrator on 2018/10/15.
*/
public class LeadTime {
private static volatile LeadTime instance;
private SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;//设置日期格式
private LeadTime() {
}
public static LeadTime getInstance() {
if (instance == null) {
synchronized (LeadTime.class) {
if (instance == null) {
instance = new LeadTime();
}
}
}
return instance;
}
/**
* 计算两个日期的时间差,精确到秒
* @param d1 日期1
* @param d2 日期2
* @return
*/
public String leadTime(Date d1, Date d2) {
// df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
Date date=new Date();//调用方法时的当前时间
String nowTime= df.format(date);
// 毫秒ms
long diff = d2.getTime() - d1.getTime();
//秒
long diffSeconds = diff / 1000 % 60;
//分
long diffMinutes = diff / (60 * 1000) % 60;
//小时
long diffHours = diff / (60 * 60 * 1000) % 24;
//天数
long diffDays = diff / (24 * 60 * 60 * 1000);
return "距离当前时间剩余" + diffDays + "天" + diffHours + "时";
}
/**
* 计算传入日期和当前时间的时间差,精确到秒
* @param d1 日期1
* @return
*/
public String leadTimeNow(Date d1) {
// df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
Date d2=new Date();//调用方法时的当前时间
// 毫秒ms
long diff = d2.getTime() - d1.getTime();
//秒
long diffSeconds = diff / 1000 % 60;
//分
long diffMinutes = diff / (60 * 1000) % 60;
//小时
long diffHours = diff / (60 * 60 * 1000) % 24;
//天数
long diffDays = diff / (24 * 60 * 60 * 1000);
return "时间差" + diffDays + "天" + diffHours + "时";
}
}
校验指定格式日期是否是当天日期
/**
* 检查任意日期是否是当天
* @param str 传入需要校验的日期字符串
* @param formatStr 日期格式 yyyy-MM-dd HH:mm:ss
* @return true 表示校验日期是当天日期
* @throws Exception
*/
public static boolean isToday(String str, String formatStr) throws Exception {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
// logger.error("解析日期错误", e);
LogUtils.e("解析日期错误", e.toString());
}
Calendar c1 = Calendar.getInstance();
c1.setTime(date);
int year1 = c1.get(Calendar.YEAR);
int month1 = c1.get(Calendar.MONTH) + 1;
int day1 = c1.get(Calendar.DAY_OF_MONTH);
Calendar c2 = Calendar.getInstance();
c2.setTime(new Date());
int year2 = c2.get(Calendar.YEAR);
int month2 = c2.get(Calendar.MONTH) + 1;
int day2 = c2.get(Calendar.DAY_OF_MONTH);
if (year1 == year2 && month1 == month2 && day1 == day2) {
return true;
}
return false;
}