Java 查找两个日期之间的总小时数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2003521/
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
Find total hours between two Dates
提问by clang1234
I have two Date objects and I need to get the time difference so I can determine the total hours between them. They happen to be from the same day. The result I would like would have the hours and minutes.
我有两个 Date 对象,我需要获取时差,以便确定它们之间的总小时数。他们恰好来自同一天。我想要的结果是小时和分钟。
When I use .toString() on my Date object I get this: Fri Dec 18 08:08:10 CST 2009
当我在我的 Date 对象上使用 .toString() 时,我得到这个: Fri Dec 18 08:08:10 CST 2009
I've tried the following:
我尝试了以下方法:
long diff=(this.endDate.getTime()-this.startDate.getTime())/(60*60 * 1000);
But this only gives me hours, not the minutes. I know this is a simple problem, but I can't figure it out atm.
但这只能给我几个小时,而不是几分钟。我知道这是一个简单的问题,但我无法弄清楚 atm。
Edits: Final solution for those interested. Thanks to Michael Brewer-Davis
编辑:感兴趣的人的最终解决方案。感谢 Michael Brewer-Davis
Period p = new Period(this.startDate, this.endDate);
long hours = p.getHours();
long minutes = p.getMinutes();
String format = String.format("%%0%dd", 2);
return Long.toString(hours)+":"+String.format(format, minutes);
采纳答案by Michael Brewer-Davis
Here's how it works with Joda time:
以下是它与Joda time 的工作方式:
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
int hours = p.getHours();
int minutes = p.getMinutes();
You could format with Joda's formatters, e.g., PeriodFormat, but I'd suggest using Java's. See this questionfor more details.
您可以使用 Joda 的格式化程序(例如 PeriodFormat)进行格式化,但我建议使用 Java 的格式化程序。有关更多详细信息,请参阅此问题。
回答by Ritwik Bose
So the getTime() method, I presume, returns an integer.
所以我认为 getTime() 方法返回一个整数。
In which case, the left set of parentheses has type int, right?
在这种情况下,左括号的类型为 int,对吗?
and
和
(60*60*1000)
is also an int.
也是一个int。
Which means you get long diff = ((int)/(int)) so the integer division is done BEFORE you cast stuff to long. And hence you lose your minutes.
这意味着你得到 long diff = ((int)/(int)) 所以整数除法在你将东西转换为 long 之前完成。因此你失去了你的分钟。
Try casting them BEFORE you divide.
在划分之前尝试投射它们。
回答by Rob Van Dam
This should work.
这应该有效。
long secs = (this.endDate.getTime() - this.startDate.getTime()) / 1000;
int hours = secs / 3600;
secs = secs % 3600;
int mins = secs / 60;
secs = secs % 60;
回答by Fayez Alrafeea
Here's simple way:
这里有一个简单的方法:
private static int hoursDifference(Date date1, Date date2) {
final int MILLI_TO_HOUR = 1000 * 60 * 60;
return (int) (date1.getTime() - date2.getTime()) / MILLI_TO_HOUR;
}
回答by sahu
Here is the simple method :-Check your Date format
,if your date not in this format then change it and pass to this method it will give you a String
which is your result. Modify the method as per the requirement.
这是一个简单的方法:-检查你Date format
的日期,如果你的日期不是这种格式,那么改变它并传递给这个方法,它会给你一个String
结果。根据要求修改方法。
private String getDateAsTime(String datePrev) {
String daysAsTime = "";
long day = 0, diff = 0;
String outputPattern = "yyyy:MM:dd HH:mm:ss";
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Calendar c = Calendar.getInstance();
String dateCurrent = outputFormat.format(c.getTime());
try {
Date date1 = outputFormat.parse(datePrev);
Date date2 = outputFormat.parse(dateCurrent);
diff = date2.getTime() - date1.getTime();
day = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
} catch (ParseException e) {
e.printStackTrace();
}
if (day == 0) {
long hour = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
if (hour == 0)
daysAsTime = String.valueOf(TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS)).concat(" minutes ago");
else
daysAsTime = String.valueOf(hour).concat(" hours ago");
} else {
daysAsTime = String.valueOf(day).concat(" days ago");
}
return daysAsTime;
}
Hope this will help,
希望这会有所帮助,
回答by Lotonoro
Please follow Somaiah's suggestion in a comment, use Hours instead:
请在评论中遵循 Somaiah 的建议,改用“时间”:
Hours hours = Hours.hoursBetween(startTime, endTime);
小时小时 = hours.hoursBetween(startTime, endTime);
The call to getHours() will only return the hour section of the time difference and ignore all year, month differences so it would not be correct in some cases.
对 getHours() 的调用将只返回时差的小时部分并忽略所有年月差,因此在某些情况下它是不正确的。
If you use Period.toStandardHours() to try to convert the time difference into hours the calculation will throw an exception if the time difference between the two dates includes difference in either year or month, since the length of month is unknown.
如果您使用 Period.toStandardHours() 尝试将时差转换为小时,则如果两个日期之间的时差包括年份或月份的差异,则计算将引发异常,因为月份的长度未知。
回答by Kishan Donga
for kotlin, you can use below function and get hours between two date
对于 kotlin,您可以使用以下函数并获取两个日期之间的小时数
private val dateFormat: String = "yyyy-MM-dd @ hh:mm a"
val startDate = SimpleDateFormat(dateFormat).parse("2018-10-01 @ 12:33 PM")
val endDate = SimpleDateFormat(dateFormat).parse("2018-10-01 @ 02:46 PM")
private fun hoursDifference(date1: Date, date2: Date): Int {
val milliToHour : Long = 1000 * 60 * 60
return ((date1.time - date2.time) / milliToHour).toInt()
}
println(hoursDifference(endDate,startDate).toString())
Output:2
输出:2
回答by Markymark
Even though there's already an accepted answer, this is what worked for me using the Joda timelibrary.
即使已经有一个可以接受的答案,这也是使用Joda 时间库对我有用的方法。
/**
*
* @param date1
* @param date2
* @return hours between two dates rounded down
*/
public static int hoursBetween(DateTime date1, DateTime date2) {
if(date1 == null || date2 == null) return NOT_FOUND;
return Math.abs(Hours.hoursBetween(date1.toLocalDateTime(), date2.toLocalDateTime()).getHours());
}
回答by Ole V.V.
java.time.Duration
java.time.Duration
I should like to contribute the modern (java 8+) answer. The solutions using Joda-Time are fine. The Joda-Time project is in maintenance mode, so for new code we should not use it. I follow the official recommendation from the Joda-Time project and use java.time, the modern Java date and time API:
我想贡献现代(java 8+)答案。使用 Joda-Time 的解决方案很好。Joda-Time 项目处于维护模式,所以对于新代码我们不应该使用它。我遵循 Joda-Time 项目的官方建议并使用 java.time,现代 Java 日期和时间 API:
Duration dur = Duration.between(startDate, endDate);
String result = String.format("%d:%02d", dur.toHours(), dur.toMinutesPart());
System.out.println(result);
This works if startDate
and endDate
both have type Instant
or OffsetDateTime
or ZonedDateTime
or LocalDateTime
or LocalTime
. All of the mentioned types are from java.time
package. If starting with LocalDate
, call either of the atStartOfDay
methods.
这个作品,如果startDate
和endDate
两者都具有类型Instant
或OffsetDateTime
或ZonedDateTime
或LocalDateTime
或LocalTime
。所有提到的类型都来自java.time
包。如果以 开头LocalDate
,则调用任一atStartOfDay
方法。
The toMinutesPart
methof was introduced in Java 9. If you are using Java 8 (ot ThreeTen Backport), search for java format duration
or similar to learn how to format the duration into hours and minutes.
该toMinutesPart
方法是在 Java 9 中引入的。如果您使用的是 Java 8(或 ThreeTen Backport),请搜索java format duration
或类似以了解如何将持续时间格式化为小时和分钟。
Two quotes from the Joda-Time home page:
来自 Joda-Time 主页的两句话:
Users are now asked to migrate to
java.time
(JSR-310).Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to
java.time
(JSR-310).
现在要求用户迁移到
java.time
(JSR-310)。请注意,Joda-Time 被认为是一个很大程度上“已完成”的项目。没有计划进行重大改进。如果使用 Java SE 8,请迁移到
java.time
(JSR-310)。
Links
链接
- Oracle tutorial: Date Timeexplaining how to use java.time.
- Joda-Time home page
- Oracle 教程:解释如何使用 java.time 的日期时间。
- Joda-Time 主页
回答by Jessica Rios
private void getHours(Date d1, Date d2){
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffDays = diff / (24 * 60 * 60 * 1000);
long diffHours = diff / (60 * 60 * 1000) % 24;
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.\n");
}`
}`
//Displays: /* 1 days, 1 hours, 1 minutes, 50 seconds. */
//显示:/* 1天1小时1分50秒。*/