首页 > 编程 > Java > 正文

java中对时间差的计算方法

2019-11-08 19:30:49
字体:
来源:转载
供稿:网友

看见网上很多时间差的记录方式,方法很多,记录一种自己觉得比较好用的

实现方式采用的是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)); 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表