您的位置:首页 > 编程语言 > Java开发

java中对时间差的计算方法

2017-02-16 11:20 423 查看
看见网上很多时间差的记录方式,方法很多,记录一种自己觉得比较好用的

实现方式采用的是SimpleDateFormat

eg:一:SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");

1.计算天数差

String starDate = simpleFormat.format("2017-02-16
12:00"); 

String endDate = simpleFormat.format("2017-01-16 12:00");

long star= simpleFormat.parse(starDate).getTime();

long end= simpleFormat.parse(endDate ).getTime();

int days = (int) ((star- end)/(1000 * 60 * 60 * 24));

getTime是将时间转换为毫秒值来计算

2.计算小时差

String starDate = simpleFormat.format("2017-02-16
12:00"); 

String
endDate = simpleFormat.format("2017-01-16 12:00");

long star= simpleFormat.parse(starDate).getTime();

long end= simpleFormat.parse(endDate ).getTime();

int hours = (int) ((to - from)/(1000 * 60 * 60));

3.计算分钟差

String starDate = simpleFormat.format("2017-02-16
12:00"); 

String
endDate = simpleFormat.format("2017-01-16 12:00");

long star= simpleFormat.parse(starDate).getTime();

long end= simpleFormat.parse(endDate ).getTime();

int minutes = (int) ((to - from)/(1000 * 60)); 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: