java 获取两个时间差_java计算两个时间差

该博客介绍了一个Java方法用于计算两个日期之间的毫秒、秒、分、时和天数差。通过使用SimpleDateFormat进行日期格式化,并进行时间单位转换,可以得到两个日期间的精确时间差。示例展示了从2020年12月12日到2021年1月1日的时间差计算,结果显示为480小时或20天。
摘要由CSDN通过智能技术生成

计算时间差:

注:时间是以毫秒来算的,一天等于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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值