有没有办法从选择器中减去两个日期。
示例:
20/10/2014
(-) 06/10/2014
--------------
14 days
答案 0 :(得分:2)
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
}
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays,
elapsedHours, elapsedMinutes, elapsedSeconds);
}
输出就是这个
startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
答案 1 :(得分:1)
由于提供的信息不多,我假设您使用的是DatePicker
基本流程是这样的:
从getDayOfMonth()
拨打getMonth()
,getYear()
和DataPicker
,分别获取日,月和年。
获得这些信息后,我认为您应该能够计算它们之间的日差。
仅供您参考,以下是关于日差的主题,希望对此有所帮助。
答案 2 :(得分:1)
短而简单
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date1 = null;
java.util.Date date2 = null;
try {
date1 = simpleDateFormat.parse("20/10/2014");
date2 = simpleDateFormat.parse("06/10/2014");
} catch (java.text.ParseException e) {
e.printStackTrace();
}
int diffInDays = (int) ((date1.getTime() - date2.getTime())/ (1000 * 60 * 60 * 24));
编辑:
Hello Uday
非常简单,你有两个EditText,所以首先将你的日期设置为et和et1,现在
et.getText().toString(); //Do same for et1 also
此方法将帮助您获取日期,现在可以应用于我的代码