两次约会之间的 Android 区别

我有两个约会,比如:

String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";

我想把它们的区别打印出来,比如:

2d 3h 45m

我怎么能这么做? 谢谢!

149696 次浏览
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

几个月后就会有所不同

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));

这可以工作并转换为 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);
}
}

您可以将其泛化为一个函数,该函数允许您选择输出格式

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();
}

当您使用 Date()计算小时差异时,必须以 UTC 格式配置 SimpleDateFormat(),否则由于夏令时,您将得到一个小时的错误。

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()

它返回给定的两个日期之间的天数,其中 DateTime来自 joda 库

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));

我用这个: 以毫秒为单位发送开始和结束日期

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

科特林版本:

@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
return try {
DurationUnit.DAYS.convert(
format.parse(newDate).time - format.parse(oldDate).time,
DurationUnit.MILLISECONDS
)
} catch (e: Exception) {
e.printStackTrace()
0
}
}

这是现代的答案。对于任何使用 Java8或更高版本的用户(目前大多数 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

在我看来,这样做的好处并不是因为它更短(并不是很长) ,而是将计算工作留给一个标准库更不容易出错,并且使您的代码更加清晰。这些都是巨大的优势。读者不需要承担识别24、60和1000这样的常量并验证它们是否被正确使用的任务。

我使用的是现代的 Java 日期和时间 API (在 JSR-310中描述,也以此名称为人所知)。要在 API 级别26下的 Android 上使用它,请获取 ThreeTenABP,参见 这个问题: 如何在 Android 项目中使用 ThreeTenABP。要与其他 Java6或7一起使用它,请获取 310后端口。在 Java8和更高版本中,它是内置的。

在 Java9中,这将会更加容易,因为 Duration类是通过方法扩展的,可以分别给出天部分、小时部分、分钟部分和秒部分,所以不需要减法。请参见 我的答案就在这里中的示例。

您可以使用此方法计算以毫秒为单位的时间差,并获得以秒、分钟、小时、天、月和年为单位的输出。

你可以从这里下载类: 日期时间差 GitHub 链接

  • 简单易用
long currentTime = System.currentTimeMillis();
long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago


Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND));
Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
  • 您可以比较下面的示例
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){
Log.d("DateTime: ", "There are more than 100 minutes difference between two dates.");
}else{
Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates.");
}

我安排了一下,效果很好。

@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
Date date = new Date();
String dateOfDay = simpleDateFormat.format(date);


String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();


@SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
try {
Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);


printDifference(date1, date2);


} catch (ParseException e) {
e.printStackTrace();
}


@SuppressLint("SetTextI18n")
private void 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;


Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}

试试这个。

int day = 0;
int hh = 0;
int mm = 0;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy 'at' hh:mm aa");
Date oldDate = dateFormat.parse(oldTime);
Date cDate = new Date();
Long timeDiff = cDate.getTime() - oldDate.getTime();
day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));






} catch (ParseException e) {
e.printStackTrace();
}


if (mm <= 60 && hh!= 0) {
if (hh <= 60 && day != 0) {
return day + " DAYS AGO";
} else {
return hh + " HOUR AGO";
}
} else {
return mm + " MIN AGO";
}

这里有一个简单的解决办法:

fun printDaysBetweenTwoDates(): Int {
val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val endDateInMilliSeconds = dateFormat.parse("26-02-2022")?.time ?: 0
val startDateInMilliSeconds = dateFormat.parse("18-02-2022")?.time ?: 0
return getNumberOfDaysBetweenDates(startDateInMilliSeconds, endDateInMilliSeconds)
}


private fun getNumberOfDaysBetweenDates(
startDateInMilliSeconds: Long,
endDateInMilliSeconds: Long
): Int {
val difference = (endDateInMilliSeconds - startDateInMilliSeconds) / (1000 * 60 * 60 * 24).toDouble()
val noOfDays = Math.ceil(difference)
return (noOfDays).toInt()
}