android 日期相减得天数,Android计算两个日期之间的天数

I have written the following code to find days between two dates

startDateValue = new Date(startDate);

endDateValue = new Date(endDate);

long diff = endDateValue.getTime() - startDateValue.getTime();

long seconds = diff / 1000;

long minutes = seconds / 60;

long hours = minutes / 60;

long days = (hours / 24) + 1;

Log.d("days", "" + days);

When start and end date are 2/3/2017 and 3/3/2017 respectively the number of days showing is 29.Though when they are of the same day it is showing 1.(The number of days one takes a leave.So if one takes a single day leave,he has to select same start and end date.So in this case he has taken two days leave).

What am I doing wrong?

Thank you for your time.

Note: Please don't use the date constructor. Check the accepted answer below. Use simpledateformat or Joda time. Date constructor is deprecated.

解决方案

Your code for generating date object:

Date date = new Date("2/3/2017"); //deprecated

You are getting 28 days as answer because according to Date(String) constructor it is thinking day = 3,month = 2 and year = 2017

You can convert String to Date as follows:

String dateStr = "2/3/2017";

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

Date date = sdf.parse(dateStr);

Use above template to make your Date object. Then use below code for calculating days in between two dates. Hope this clear the thing.

It can de done as follows:

long diff = endDateValue.getTime() - startDateValue.getTime();

System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));

Please check link

If you use Joda Time it is much more simple:

int days = Days.daysBetween(date1, date2).getDays();

Please check JodaTime

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值