我有两个日期格式的时间戳。
如何获取给定范围内存在的天数?
SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
Date begin=sdf.parse("27 02 2014 23:00:00");
Date end=sdf.parse("01 03 2014 00:00:10");
在上面的例子中它必须是3,即(2月27日、2月28日和1月1日)
int days = (int) (end.getTime() - begin.getTime())/(1000*3600*24) ;
上述方法没有帮助,因为它考虑了整个时间戳。
最佳答案
您可以使用 JodaTime。
import org.joda.*;
import org.joda.time.*;
DateTime start = new DateTime(2014, 02, 27, 0, 0, 0, 0);
DateTime end = new DateTime(2014, 03, 1, 01, 0, 0, 0);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
int days = period.getDays();
更多信息here .
但是,如果您想查找某个范围内的天数而不考虑小时,而只考虑日、月和年...为什么不完全按照您正在做的操作,而是仅解析日期以获得日、月、年?这样,您用来计算天数的公式就始终有效。
关于java - 查找天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25012002/