两个日期之间的Android差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21285161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android difference between Two Dates
提问by D Ferra
I have two date like:
我有两个约会,例如:
String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";
I want to print the difference like:
我想打印如下差异:
2d 3h 45m
How can I do that? Thanks!
我怎样才能做到这一点?谢谢!
回答by Digvesh Patel
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);
}
out put is :
输出是:
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
回答by TheVinceble
This works and convert to String as a Bonus ;)
这有效并转换为字符串作为奖励;)
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);
}
}
回答by Nilesh Savaliya
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));
回答by Meet
Short & Sweet:
简短而甜蜜:
/**
* 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;
}
}
Usage:
用法:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);
Output:
输出:
dateDifference: 2
Kotlin Version:
科特林版本:
@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
}
}
回答by Swap-IOS-Android
It will give you difference in months
它会让你在几个月内有所不同
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));
回答by subrahmanyam boyapati
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()
it returns how many days between given two dates, where DateTime
is from joda library
它返回给定两个日期之间的天数,DateTime
来自 joda 库
回答by A. Batuhan ?zkaya
You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.
您可以使用此方法计算以毫秒为单位的时间差,并以秒、分钟、小时、天、月和年为单位获得输出。
You can download class from here: DateTimeDifference GitHub Link
你可以从这里下载类:DateTimeDifference GitHub Link
- Simple to use
- 使用简单
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));
- You can compare the example below
- 你可以比较下面的例子
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."); }
回答by Trk
I arranged a little. This works great.
我稍微安排了一下。这很好用。
@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();
}
回答by Vijay Singh Chouhan
Try this out.
试试这个。
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";
}
回答by Ole V.V.
Here is the modern answer. It's good for anyone who either uses Java 8 or later (which doesn't go for most Android phones yet) or is happy with an external library.
这是现代答案。这对于使用 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();
}
This prints
这打印
2d 3h 45m
In my own opinion the advantage is not so much that it is shorter (it's not much), but leaving the calculations to an standard library is less errorprone and gives you clearer code. These are great advantages. The reader is not burdened with recognizing constants like 24, 60 and 1000 and verifying that they are used correctly.
在我自己看来,优势不是它更短(它不是很多),而是将计算留给标准库更不容易出错,并为您提供更清晰的代码。这些都是很大的优势。读者无需承担识别 24、60 和 1000 等常量并验证它们是否正确使用的负担。
I am using the modern Java date & time API (described in JSR-310 and also known under this name). To use this on Android under API level 26, get the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. To use it with other Java 6 or 7, get ThreeTen Backport. With Java 8 and later it is built-in.
我正在使用现代 Java 日期和时间 API(在 JSR-310 中进行了描述,也以此名称为人所知)。要在 API 级别 26 下在 Android 上使用它,请获取 ThreeTenABP,请参阅此问题:如何在 Android 项目中使用 ThreeTenABP。要将其与其他 Java 6 或 7 一起使用,请获取ThreeTen Backport。在 Java 8 及更高版本中,它是内置的。
With Java 9 it will be still a bit easier since the Duration
class is extended with methods to give you the days part, hours part, minutes part and seconds part separately so you don't need the subtractions. See an example in my answer here.
使用 Java 9,它仍然会更容易一些,因为Duration
该类扩展了方法,分别为您提供了天部分、小时部分、分钟部分和秒部分,因此您不需要减法。请参阅我在此处的回答中的示例。