在if else中我进行转换(但条件不准确)
import java.util.concurrent.TimeUnit;
import java.math.RoundingMode;
import java.text.DecimalFormat;
if (field_Date1 == null || field_Date2 == null){
return "";
} else {
Date startDate = (Date)field_Date1;
Date endDate = (Date)field_Date2;
long duration = endDate.getTime() - startDate.getTime();
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
long diff = duration - TimeUnit.DAYS.toMillis(diffInDays);
double diffToHours = TimeUnit.MILLISECONDS.toHours(diff);
float hoursToDay = (float) (diffToHours / 24.0);
float a =hoursToDay+diffInDays;
a=Math.floor(a)
int b = (int)a
if(b<30)
{
StringBuilder sb = new StringBuilder("Day: ")
sb.append(b)
String c = sb.toString()
c
}
else if(b<366)
{
int months = b/30
int days_out=b%30
StringBuilder p1 = new StringBuilder("Days: ")
StringBuilder p2 = new StringBuilder("Months: ")
StringBuilder p3 = new StringBuilder(" ")
p1.append(days_out)
p2.append(months)
p2.append(p3)
p2.append(p1)
String c=p2.toString()
c
}
else
{
StringBuilder p1 = new StringBuilder("Months: ")
StringBuilder p2 = new StringBuilder("Years: ")
StringBuilder p3 = new StringBuilder(" ")
StringBuilder p4 = new StringBuilder("Days: ")
int years = b/365
int days_out=b%365
if(days_out>30)
{
int m1 = days_out/30
int m2 = days_out%30
p2.append(years)
p1.append(m1)
p4.append(m2)
p2.append(p3)
p2.append(p1)
p2.append(p3)
p2.append(p4)
String hj = p2.toString()
return hj
}
else
{
p4.append(days_out)
p2.append(years)
p2.append(p3)
p2.append(p4)
String c=p2.toString()
return c
}
}
}
答案 0 :(得分:2)
尝试使用Joda-Time 2.5:
Snippet看起来像这样:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;
Date startDate = (Date)field_Date1;
Date endDate = (Date)field_Date2;
int days = Days.daysBetween( new DateTime(startDate), new DateTime(endDate) ).getDays();
或者可以使用java.time(Java8)中的以下方法:
public static Period between(LocalDate startDateInclusive,
LocalDate endDateExclusive)
这将获得两个日期之间的时间段,包括年数,月数和日数。
答案 1 :(得分:1)
如果您想要以天为单位的两个日期之间的差异,包括考虑闰年等,java.time package(Java 8中的新功能)可以为您提供:
LocalDate firstDate = LocalDate.of(2014, Month.DECEMBER, 1);
LocalDate secondDate = LocalDate.of(2016, Month.MARCH, 12);
long days = firstDate.until(secondDate,ChronoUnit.DAYS);
给你467天。
可替换地,
Period period = firstDate.until(secondDate);
会给你一个Period对象,它存储分解为年,月和日的时间。而不是467天,你得到1年,3个月和11天。这有利于人类的可读性。但是,如果你想要总天数,那么从Period对象中获取它是不容易的,所以你最好选择我给的第一个选项。