Android计算两个日期之间的天数 [英] Android calculate days between two dates
问题描述
我编写了以下代码来查找两个日期之间的日期
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);
当开始日期和结束日期分别为2/3/2017和3/3/2017时,显示的天数为29.尽管它们是同一天,却显示1.请假.因此,如果要请一天假,他必须选择相同的开始日期和结束日期.因此,在这种情况下,他请了两天假.
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.
注意:请不要使用日期构造函数.检查下面接受的答案.使用simpledateformat或Joda时间.日期构造函数已弃用.
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
您将得到28天的答案,因为根据Date(String)
构造函数,它认为日期= 3,month = 2,年份= 2017
You are getting 28 days as answer because according to Date(String)
constructor it is thinking day = 3,month = 2 and year = 2017
您可以按以下方式将String转换为Date:
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);
使用上面的模板制作Date对象.然后使用下面的代码计算两个日期之间的天数.希望这件事能解决.
Use above template to make your Date object. Then use below code for calculating days in between two dates. Hope this clear the thing.
可以完成以下操作:
long diff = endDateValue.getTime() - startDateValue.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
请检查链接
如果您使用Joda Time,它将更加简单:
If you use Joda Time it is much more simple:
int days = Days.daysBetween(date1, date2).getDays();
请检查 JodaTime
这篇关于Android计算两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!