我在这里看到了所有的帖子,但我仍然无法弄清楚两个安卓日期之间的差异。
这就是我所做的:
long diff = date1.getTime() - date2.getTime();
Date diffDate = new Date(diff);
我得到:日期是 1970 年 1 月 1 日,两个小时内的时间总是更长……我来自以色列,所以两个小时是 timeOffset。
我怎样才能得到正常的差异???
你接近正确的答案,你得到了这两个日期之间的毫秒差异,但是当你试图从这个差异中构造一个日期时,它假设你想要创建一个新的Date
对象,该差异值作为它的纪元时间。如果您正在寻找以小时为单位的时间,那么您只需要对其进行一些基本的算术运算diff
即可获得不同的时间部分。
爪哇:
long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
科特林:
val diff: Long = date1.getTime() - date2.getTime()
val seconds = diff / 1000
val minutes = seconds / 60
val hours = minutes / 60
val days = hours / 24
所有这些数学运算都将简单地进行整数运算,因此它将截断任何小数点
long diffInMillisec = date1.getTime() - date2.getTime();
long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec);
long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillisec);
long diffInMin = TimeUnit.MILLISECONDS.toMinutes(diffInMillisec);
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
一些补充: 在这里我将字符串转换为日期,然后比较当前时间。
String toyBornTime = "2014-06-18 12:56:50";
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
try {
Date oldDate = dateFormat.parse(toyBornTime);
System.out.println(oldDate);
Date currentDate = new Date();
long diff = currentDate.getTime() - oldDate.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
if (oldDate.before(currentDate)) {
Log.e("oldDate", "is previous date");
Log.e("Difference: ", " seconds: " + seconds + " minutes: " + minutes
+ " hours: " + hours + " days: " + days);
}
// Log.e("toyBornTime", "" + toyBornTime);
} catch (ParseException e) {
e.printStackTrace();
}
使用java.time.Duration
:
Duration diff = Duration.between(instant2, instant1);
System.out.println(diff);
这将打印类似
PT109H27M21S
这意味着 109 小时 27 分 21 秒的时间段。如果你想要一些更易读的东西——我会先给出 Java 9 版本,它最简单:
String formattedDiff = String.format(Locale.ENGLISH,
"%d days %d hours %d minutes %d seconds",
diff.toDays(), diff.toHoursPart(), diff.toMinutesPart(), diff.toSecondsPart());
System.out.println(formattedDiff);
现在我们得到
4 days 13 hours 27 minutes 21 seconds
该类Duration
是java.time
现代 Java 日期和时间 API 的一部分。这捆绑在较新的 Android 设备上。在旧设备上,获取 ThreeTenABP 并将其添加到您的项目中,并确保org.threeten.bp.Duration
从同一个包中导入您可能需要的其他日期时间类。
假设您还没有获得 Java 9 版本,您可以依次减去较大的单位以获得较小的单位:
long days = diff.toDays();
diff = diff.minusDays(days);
long hours = diff.toHours();
diff = diff.minusHours(hours);
long minutes = diff.toMinutes();
diff = diff.minusMinutes(minutes);
long seconds = diff.toSeconds();
然后你可以像上面那样格式化四个变量。
ADate
代表一个时间点。它从来都不是用来代表时间量、持续时间的,也不适合它。试图使这项工作充其量只会导致混乱和难以维护的代码。你不想这样,所以请不要。
java.time 在较旧和较新的 Android 设备上都能很好地工作。它只需要至少Java 6。
org.threeten.bp
子包中导入日期和时间类。java.time
。java.time
到 Java 6 和 7使用Instant怎么样:
val instant1 = now()
val instant2 = now()
val diff: Duration = Duration.between(instant1, instant2)
val minutes = diff.toMinutes()
您甚至可以使用 Instant1.toString() 保存 Instant 并使用 parse(string) 解析该字符串。
如果您需要支持 Android API 级别 < 26,只需 在您的项目中添加Java 8+ API 脱糖支持。
如果你使用 Kotlin 语言进行 Android 开发,你可以在这样的日子里获得不同:
fun daysDiff(c1: Calendar, c2: Calendar): Long {
val diffInMillis = c1.timeInMillis - c2.timeInMillis
return diffInMillis.milliseconds.inWholeDays
}
或者,如果您想获得不同类型的结果,您可以替换inWholeDays
为toInt(...)
, toDouble(...)
, toString(...)
。
如果您感兴趣的唯一日期差异是天数(假设是 Double 类型的结果),您可以像这样创建运算符扩展方法:
operator fun Calendar.minus(c: Calendar): Double {
val diffInMillis = timeInMillis - c.timeInMillis
return diffInMillis.milliseconds.toDouble(DurationUnit.DAYS)
}
然后任何类似的操作calendar2 - calendar1
都会以双倍的天数返回差异。
这是我基于@Ole VV 回答的回答。
这也适用于单数。
private String getDuration(Date d1, Date d2) {
Duration diff = Duration.between(d1.toInstant(), d2.toInstant());
long days = diff.toDays();
diff = diff.minusDays(days);
long hours = diff.toHours();
diff = diff.minusHours(hours);
long minutes = diff.toMinutes();
diff = diff.minusMinutes(minutes);
long seconds = diff.toMillis();
StringBuilder formattedDiff = new StringBuilder();
if(days!=0){
if(days==1){
formattedDiff.append(days + " Day ");
}else {
formattedDiff.append(days + " Days ");
}
}if(hours!=0){
if(hours==1){
formattedDiff.append(hours + " hour ");
}else{
formattedDiff.append(hours + " hours ");
}
}if(minutes!=0){
if(minutes==1){
formattedDiff.append(minutes + " minute ");
}else{
formattedDiff.append(minutes + " minutes ");
}
}if(seconds!=0){
if(seconds==1){
formattedDiff.append(seconds + " second ");
}else{
formattedDiff.append(seconds + " seconds ");
}
}
return formattedDiff.toString();
}
它与 StringBuilder 一起工作以将所有内容附加在一起。
我试过这个方法..但不知道为什么我没有得到正确的结果
long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
但这有效
long miliSeconds = date1.getTime() -date2.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds);
long minute = seconds/60;
long hour = minute/60;
long days = hour/24;
使用格鲁吉亚压延机
public void dateDifferenceExample() {
// Set the date for both of the calendar instance
GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02,5,23,43);
GregorianCalendar cal2 = new GregorianCalendar(2015, 04, 02);
// Get the represented date in milliseconds
long millis1 = calDate.getTimeInMillis();
long millis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = millis2 - millis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
Toast.makeText(getContext(), ""+diffSeconds, Toast.LENGTH_SHORT).show();
}
使用这些功能
public static int getDateDifference(
int previousYear, int previousMonthOfYear, int previousDayOfMonth,
int nextYear, int nextMonthOfYear, int nextDayOfMonth,
int differenceToCount){
// int differenceToCount = can be any of the following
// Calendar.MILLISECOND;
// Calendar.SECOND;
// Calendar.MINUTE;
// Calendar.HOUR;
// Calendar.DAY_OF_MONTH;
// Calendar.MONTH;
// Calendar.YEAR;
// Calendar.----
Calendar previousDate = Calendar.getInstance();
previousDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
// month is zero indexed so month should be minus 1
previousDate.set(Calendar.MONTH, previousMonthOfYear);
previousDate.set(Calendar.YEAR, previousYear);
Calendar nextDate = Calendar.getInstance();
nextDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
// month is zero indexed so month should be minus 1
nextDate.set(Calendar.MONTH, previousMonthOfYear);
nextDate.set(Calendar.YEAR, previousYear);
return getDateDifference(previousDate,nextDate,differenceToCount);
}
public static int getDateDifference(Calendar previousDate,Calendar nextDate,int differenceToCount){
// int differenceToCount = can be any of the following
// Calendar.MILLISECOND;
// Calendar.SECOND;
// Calendar.MINUTE;
// Calendar.HOUR;
// Calendar.DAY_OF_MONTH;
// Calendar.MONTH;
// Calendar.YEAR;
// Calendar.----
//raise an exception if previous is greater than nextdate.
if(previousDate.compareTo(nextDate)>0){
throw new RuntimeException("Previous Date is later than Nextdate");
}
int difference=0;
while(previousDate.compareTo(nextDate)<=0){
difference++;
previousDate.add(differenceToCount,1);
}
return difference;
}
用 Kotlin 编写: 如果您需要两个日期之间的差异并且不关心日期本身(如果您需要在应用程序中做某事,例如基于保存在共享首选项中的其他操作时间的时间)。第一次保存:
val firstTime:Long= System.currentTimeMillis()
第二次保存:
val now:Long= System.currentTimeMillis()
计算 2 次之间的毫秒数:
val milisecondsSinceLastTime: Long =(now-lastScrollTime)
获取上午和下午之间的时差
private int getTimeDiff() {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");
Date systemDate = Calendar.getInstance().getTime();
String myDate = sdf.format(systemDate);
Date current = null;
Date Date2 = null;
try {
current = sdf.parse(myDate);
// current = sdf.parse("05:00:00 pm");
Date2 = sdf.parse("12:00:00 am");
} catch (ParseException e) {
e.printStackTrace();
}
long millse = Date2.getTime() - current.getTime();
long mills = Math.abs(millse);
int Hours = (int) (mills / (1000 * 60 * 60));
int Mins = (int) (mills / (1000 * 60)) % 60;
long Secs = (int) (mills / 1000) % 60;
String diff = Hours + ":" + Mins + ":" + Secs;
int min = 60-Mins;
if (Hours >= 12) {
String requiredTime = 24 - Hours + ":" + Mins + ":" + Secs;
int minutes= ((24-Hours)*60)-Mins;
return minutes;
} else {
int time = 12 - Hours;
int hours=time+12;
int res = (hours*60);
int minutes = res-Mins;
return minutes;
}
}
当您尝试根据该差异构造日期时,假设您要创建一个新的 Date 对象,该差异值作为其纪元时间。
//get time in milliseconds
long diff = date1.getTime() - date2.getTime();
//get time in seconds
long seconds = diff / 1000;
//and so on
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
有关更多信息,您可以使用以下链接:
Oracle 教程:日期时间,解释如何使用 java.time。
ThreeTen Backport 项目,java.time 到 Java 6 和 7 的反向移植。
ThreeTenABP , ThreeTen Backport 的 Android 版本。
问题:如何在Android项目中使用ThreeTenABP,有非常详尽的解释。
对我有用的最短答案。以毫秒为单位发送开始和结束日期。
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;
}