计算java中两个日期之间的天数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38046951/
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
Calculate no of days between two dates in java
提问by AngryJS
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
我需要计算两个日期之间的天数,我正在使用下面的代码。问题是它返回了我 2 但实际上它应该返回 3,因为 2016 年 6 月 30 日到 6 月 27 日之间的差异是 3。你能帮我看看它应该包括当前日期的差异吗?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
到期日期为 2016-06-30,当前日期为 2016-06-27
采纳答案by PyThon
Reason is, you are not subtracting two dates with same time format.
原因是,您没有减去具有相同时间格式的两个日期。
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
使用 Calendar 类将两个日期的时间更改为 00:00:00,您将获得精确的天数差异。
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Jim Garrison 的回答中有更多解释
回答by Jim Garrison
The problem is that
问题是
Date createdDate = new Date();
sets createdDate
to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00
.
设置createdDate
为当前时刻,即包括当前时间和日期。当您使用给定格式解析字符串时,时间被初始化为00:00:00
.
Let's say you ran this at exactly 18:00 local time, you end up with
假设您在当地时间 18:00 运行此程序,结果是
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
区别是 2 天 6 小时,而不是 3 天。
You should be using the newer java.time.*
classes from Java 8. There is a class LocalDate
that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now()
to get the current date, as well as methods for calculating intervals between LocalDate
instances.
您应该使用java.time.*
Java 8 中较新的类。有一个类LocalDate
表示没有时间的日期。它包括使用格式解析和LocalDate.now()
获取当前日期的方法,以及计算LocalDate
实例之间间隔的方法。
回答by yash sachdeva
Using the Calendar.get(Calendar.DAY_OF_MONTH)
as pointed out by python:
使用Calendar.get(Calendar.DAY_OF_MONTH)
python所指出的:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);
回答by Balázs édes
Why not use LocalDate
?
为什么不使用LocalDate
?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}