这篇文章将使用两个例子计算两个日期的时间差
使用Java SDK
使用Joda库
使用Java SDK
计算两个Date之间的时间差基本思路为把Date转换为ms(微秒)然后计算两个微秒时间差时间的兑换规则如下
s秒 = ms毫秒 min分种 = s秒 hours小时 = min分钟 day天 = hours小时
package comqiyadengdate;
import javatextSimpleDateFormat;
import javautilDate;
public class DateDifferentExample {
public static void main(String[] args) {
String dateStart = ::;
String dateStop = ::;
SimpleDateFormat format = new SimpleDateFormat(yyyyMMdd HH:mm:ss);
Date d = null;
Date d = null;
try {
d = formatparse(dateStart);
d = formatparse(dateStop);
//毫秒ms
long diff = dgetTime() dgetTime();
long diffSeconds = diff / % ;
long diffMinutes = diff / ( * ) % ;
long diffHours = diff / ( * * ) % ;
long diffDays = diff / ( * * * );
Systemoutprint(两个时间相差);
Systemoutprint(diffDays + 天 );
Systemoutprint(diffHours + 小时 );
Systemoutprint(diffMinutes + 分钟 );
Systemoutprint(diffSeconds + 秒);
} catch (Exception e) {
eprintStackTrace();
}
}
}
运行结果
两个时间相差 天 小时 分钟 秒
Joda时间库
package comqiyadengdate;
import javatextSimpleDateFormat;
import javautilDate;
import orgjodatimeDateTime;
import orgjodatimeDays;
import orgjodatimeHours;
import orgjodatimeMinutes;
import orgjodatimeSeconds;
public class JodaDateDifferentExample {
public static void main(String[] args) {
String dateStart = ::;
String dateStop = ::;
SimpleDateFormat format = new SimpleDateFormat(yyyyMMdd HH:mm:ss);
Date d = null;
Date d = null;
try {
d = formatparse(dateStart);
d = formatparse(dateStop);
DateTime dt = new DateTime(d);
DateTime dt = new DateTime(d);
Systemoutprint(两个时间相差);
Systemoutprint(DaysdaysBetween(dt dt)getDays() + 天 );
Systemoutprint(HourshoursBetween(dt dt)getHours() %
+ 小时 );
Systemoutprint(MinutesminutesBetween(dt dt)getMinutes() %
+ 分钟 );
Systemoutprint(SecondssecondsBetween(dt dt)getSeconds() %
+ 秒);
} catch (Exception e) {
eprintStackTrace();
}
}
}
运行结果
两个时间相差 天 小时 分钟 秒