>百科大全> 列表
时间比较大小的公式
时间:2025-04-14 18:26:00
答案

1.Date的getTime方法,来获取时间,然后对两个时间进行比较。

1

2

3

4

5

6

7

8

9

10

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date oldDate1 = format.parse("2017-03-12 59:16:00");

Date oldDate2 = format.parse("2018-02-06 23:16:00");

if(d1.getTime() > d2.getTime()){

return 1;

}else if(d1.getTime() < d2.getTime()){

return -1;

}else{

return 0;

}

1

2

3

4

5

6

7

8

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date oldDate1 = format.parse("2017-03-12 59:16:00");

Date oldDate2 = format.parse("2018-02-06 23:16:00");

long day=num/(24*60*60*1000);

long hour=(num/(60*60*1000)-day*24);

long min=((num/(60*1000))-day*24*60-hour*60);

long s=(num/1000-day*24*60*60-hour*60*60-min*60);

System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");

2.Date中compareTo的用法。也是比较时间大小的,相等返回0,大于返回1,小于返回-1

1

2

3

4

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date oldDate1 = format.parse("2017-03-12 59:16:00");

Date oldDate2 = format.parse("2018-02-06 23:16:00");

System.out.println(oldDate1.compareTo(oldDate2));

推荐
Copyright © 2025 好久知识网 |  琼ICP备2022020623号 |  网站地图