java计算两个时间差


计算时间差:

注:时间是以毫秒来算的,一天等于24小时,一小时等于60分钟,一分钟等于60秒,一秒等于1000毫秒!

private int formatDate(Date nowDate, Date sqlDate){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String newDate = df.format(nowDate);
String sqlDate1 = df.format(sqlDate);
try {
nowDate = df.parse(newDate);
sqlDate = df.parse(sqlDate1);
} catch (ParseException e) {
e.printStackTrace();
}
Long time = nowDate.getTime();
Long time2 = sqlDate.getTime();
int day = (int) ((time - time2) / (24*3600*1000));
return day;
}

 

一.毫秒

  int millisecond = (int)(time - time2) / (1)

二.秒

  int second = (int)(time - time2) / (1000 )

1000 为 1 秒钟   

三.分

  int Minutes = (int)(time - time2) / (1000 * 60 )

1000 为 1 秒钟   1000*60 为 1 分钟 

四.时

  int hours = (int)(time - time2) / (1000 * 60 * 60)

1000 为 1 秒钟   1000*60 为 1 分钟 1000*60*60 为 1 小时

五.天

  int day = (int) ((time - time2) / ( 1000 * 60 * 60 * 24);

 1000 为 1 秒钟   1000*60 为 1 分钟 1000*60*60 为 1 小时     1000 * 60 * 60 * 24 为 1 天

 

 

例子: 2021-01-01 00:00:00   和   2020-12-12 00:00:00

一,相毫秒,秒,分,时,天
@Test
public void test(){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try {
System.out.println(formatDate(df.parse("2021-01-01 23:59:59"),df.parse("2020-12-12 00:00:00")));
} catch (ParseException e) {
e.printStackTrace();
}
}


结果:

毫秒:1728000000 秒:1728000 分: 28800 时: 480 天 20

时间差(年月) ------------>https://blog.csdn.net/FengRenYuanDeFZ/article/details/102551550?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM