我在我的Android应用程序中有一个日期选择器。 我想获得所选日期和今天日期之间的差异日。
我的结果:
E/-->: DatePicker: 1448798400691 // 29.11.2015
E/-->: NOW: 1448920633692
E/-->: DIFF: -1
E/-->: DatePicker: 1448884800191 // 30.11.2015
E/-->: NOW: 1448920637192
E/-->: DIFF: 0
E/-->: DatePicker: 1448971200451 // 01.12.2015
E/-->: NOW: 1448920644463
E/-->: DIFF: 0
答案 0 :(得分:1)
您可以按如下方式计算差异。获取日期使用以下代码。
//从时间选择器获取日期
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 0, 0, 0); //use object of Datepicker widget
long diff = calendar.getTimeInMillis() - System.currentTimeMillis(); //calculate difference
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff); //here you will have diff in seconds.
long daysdiff = TimeUnit.MILLISECONDS.toDays(diff); //if you want diff in days
答案 1 :(得分:1)
你应该试试这个
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date past = format.parse("12/10/2015 18:10:52");
Date now = new Date();
System.out.println(TimeUnit.MILLISECONDS.toSeconds(now.getTime() - past.getTime()) + " seconds ago");
System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");
您可以在format.parse("")
中以指定格式
答案 2 :(得分:0)
您可以使用此方法来获取两个日期之间的差异。
public static int getDateDifference(long startDate, long endDate) {
//milliseconds
long different = endDate - startDate;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
return (int) elapsedDays;
}
答案 3 :(得分:0)
试试这个
public static long printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
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;
return elapsedDays;
}
答案 4 :(得分:0)
尝试这个例子来解决
String dateStart = "11/28/2015 09:29:58";
String dateStop = "11/29/2015 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
}
catch(Exception e){}