两个date之间的Android差异
我有两个date,如:
String date_1="yyyyMMddHHmmss"; String date_2="yyyyMMddHHmmss";
我想要打印的差异,如:
2d 3h 45m
我怎样才能做到这一点? 谢谢!
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
这工作,并转换为string作为奖金;)
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { //Dates to compare String CurrentDate= "09/24/2015"; String FinalDate= "09/26/2015"; Date date1; Date date2; SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy"); //Setting dates date1 = dates.parse(CurrentDate); date2 = dates.parse(FinalDate); //Comparing dates long difference = Math.abs(date1.getTime() - date2.getTime()); long differenceDates = difference / (24 * 60 * 60 * 1000); //Convert long to String String dayDifference = Long.toString(differenceDates); Log.e("HERE","HERE: " + dayDifference); } catch (Exception exception) { Log.e("DIDN'T WORK", "exception " + exception); } }
它会给你几个月的差异
long milliSeconds1 = calendar1.getTimeInMillis(); long milliSeconds2 = calendar2.getTimeInMillis(); long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000; long elapsedDays = periodSeconds / 60 / 60 / 24; System.out.println(String.format("%d months", elapsedDays/30));
Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob); Date today = new Date(); long diff = today.getTime() - userDob.getTime(); int numOfDays = (int) (diff / (1000 * 60 * 60 * 24)); int hours = (int) (diff / (1000 * 60 * 60)); int minutes = (int) (diff / (1000 * 60)); int seconds = (int) (diff / (1000));
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale); DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale); Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
它会返回给定的两个date之间多less天,其中DateTime
来自joda库
你可以把它推广到一个让你select输出格式的函数
private String substractDates(Date date1, Date date2, SimpleDateFormat format) { long restDatesinMillis = date1.getTime()-date2.getTime(); Date restdate = new Date(restDatesinMillis); return format.format(restdate); }
现在是这样一个简单的函数调用,小时,分钟和秒的差异:
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date1 = formater.parse(dateEnd); Date date2 = formater.parse(dateInit); String result = substractDates(date1, date2, new SimpleDateFormat("HH:mm:ss")); txtTime.setText(result); } catch (ParseException e) { e.printStackTrace(); }
您可以使用此方法计算以毫秒为单位的时间差,并以秒,分,小时,天,月和年获得输出。
你可以从这里下载类: DateTimeDifference GitHub链接
- 简单易用
long currentTime = System.currentTimeMillis(); long previousTime =(System.currentTimeMillis() - 864000000); // 10天前 Log.d(“DateTime:”,“与第二个差异:”+ AppUtility.DateTimeDifference(currentTime,previousTime,AppUtility.TimeDifference.SECOND)); Log.d(“DateTime:”,“与分钟差异:”+ AppUtility.DateTimeDifference(currentTime,previousTime,AppUtility.TimeDifference.MINUTE));
- 你可以比较下面的例子
if(AppUtility.DateTimeDifference(currentTime,previousTime,AppUtility.TimeDifference.MINUTE)> 100){ Log.d(“DateTime:”,“两个date之间有超过100分钟的差异”); }其他{ Log.d(“DateTime:”,“两个date之间不超过100分钟的差异”); }
当您使用Date()
来计算以小时为单位的差异时,必须以UTCconfigurationSimpleDateFormat()
,否则由于Daylight SavingTime会出现一小时的错误。
我用这个:以毫秒为单位发送开始和结束date
public int GetDifference(long start,long end){ Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(start); int hour = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); long t=(23-hour)*3600000+(59-min)*60000; t=start+t; int diff=0; if(end>t){ diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1; } return diff; }
短而甜:
/** * Get a diff between two dates * * @param oldDate the old date * @param newDate the new date * @return the diff value, in the days */ public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) { try { return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS); } catch (Exception e) { e.printStackTrace(); return 0; } }
用法:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017"); System.out.println("dateDifference: " + dateDifference);
输出:
dateDifference: 2
这是现代的答案。 对于任何使用Java 8或更高版本(对大多数Android手机都不适用)或对外部库感到满意的人来说,这是一件好事。
String date1 = "20170717141000"; String date2 = "20170719175500"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); Duration diff = Duration.between(LocalDateTime.parse(date1, formatter), LocalDateTime.parse(date2, formatter)); if (diff.isZero()) { System.out.println("0m"); } else { long days = diff.toDays(); if (days != 0) { System.out.print("" + days + "d "); diff = diff.minusDays(days); } long hours = diff.toHours(); if (hours != 0) { System.out.print("" + hours + "h "); diff = diff.minusHours(hours); } long minutes = diff.toMinutes(); if (minutes != 0) { System.out.print("" + minutes + "m "); diff = diff.minusMinutes(minutes); } long seconds = diff.getSeconds(); if (seconds != 0) { System.out.print("" + seconds + "s "); } System.out.println(); }
这打印
2d 3h 45m
在我看来,优点不在于它比较短(不是很多),而是将计算结果保存到一个标准的库中,这样做可以减less错误的发生,并且使代码更加清晰。 这些是很大的优点。 读者不需要承认像24,60和1000这样的常量,并validation它们的使用是否正确。
我正在使用现代化的Javadate和时间API(在JSR-310中进行了介绍,并且以该名称为人所知)。 在Android上使用这个,得到ThreeTenABP,看到这个问题:如何在Android项目中使用ThreeTenABP 。 要与其他Java 6或7一起使用,请获取ThreeTen Backport 。 对于Java 8及更高版本,它是内置的。
对于Java 9来说,它会更容易一些,因为Duration
类是通过扩展方法来分别给出部分,小时部分,分钟部分和秒部分,所以你不需要减法。 在我的答案在这里看到一个例子。