Android计算两个日期之间的天数

时间:2017-03-02 10:36:53

标签: java android date datetime

我写了以下代码来查找两个日期之间的天数

    startDateValue = new Date(startDate);
    endDateValue = new Date(endDate);
    long diff = endDateValue.getTime() - startDateValue.getTime();
    long seconds = diff / 1000;
    long minutes = seconds / 60;
    long hours = minutes / 60;
    long days = (hours / 24) + 1;
    Log.d("days", "" + days);

当开始和结束日期分别为2017年2月3日和2017年3月3日时,显示的天数为29.尽管它们显示的是同一天,但是显示的天数为1天。如果一个人休一天假,他必须选择相同的开始和结束日期。所以在这种情况下,他已经休了两天假。)

我做错了什么? 谢谢你的时间。

注意:请不要使用日期构造函数。检查下面接受的答案。使用simpledateformat或Joda时间。不建议使用日期构造函数。

14 个答案:

答案 0 :(得分:24)

生成日期对象的代码:

Date date = new Date("2/3/2017"); //deprecated

你得到了28天的回答,因为根据Date(String)构造函数,它认为日= 3,月= 2和年= 2017

您可以将String转换为Date,如下所示:

String dateStr = "2/3/2017";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateStr);

使用上面的模板制作Date对象。然后使用下面的代码计算两个日期之间的天数。希望这清楚这件事。

它可以如下完成:

long diff = endDateValue.getTime() - startDateValue.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));

请检查link

如果你使用Joda Time,那就更简单了:

int days = Days.daysBetween(date1, date2).getDays();

请检查JodaTime

How to use JodaTime in Java Project

答案 1 :(得分:8)

public static int getDaysDifference(Date fromDate,Date toDate)
{
if(fromDate==null||toDate==null)
return 0;

return (int)( (toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));
}

答案 2 :(得分:4)

Android是否完全支持java-8?如果是,您可以简单地使用ChronoUnit class

LocalDate start = LocalDate.of(2017,2,3);
LocalDate end = LocalDate.of(2017,3,3);

System.out.println(ChronoUnit.DAYS.between(start, end)); // 28

或使用格式化程序

的相同内容
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate start = LocalDate.parse("2/3/2017",formatter);
LocalDate end = LocalDate.parse("3/3/2017",formatter);

System.out.println(ChronoUnit.DAYS.between(start, end)); // 28

答案 3 :(得分:4)

您使用什么日期格式?是d/M/yyyy还是M/d/yyyy

d =天,M =月,yyyy =年

(见:https://developer.android.com/reference/java/text/SimpleDateFormat.html

然后是代码:

public static final String DATE_FORMAT = "d/M/yyyy";  //or use "M/d/yyyy"   

public static long getDaysBetweenDates(String start, String end) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
    Date startDate, endDate;
    long numberOfDays = 0;
    try {
        startDate = dateFormat.parse(start);
        endDate = dateFormat.parse(end);
        numberOfDays = getUnitBetweenDates(startDate, endDate, TimeUnit.DAYS);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return numberOfDays;
}

对于getUnitBetweenDates方法:

private static long getUnitBetweenDates(Date startDate, Date endDate, TimeUnit unit) {
    long timeDiff = endDate.getTime() - startDate.getTime();
    return unit.convert(timeDiff, TimeUnit.MILLISECONDS);
}

答案 4 :(得分:4)

科特林

以下是计算从今天到某个日期的天数的示例:

 val millionSeconds = yourDate.time - Calendar.getInstance().timeInMillis
 leftDays.text = TimeUnit.MILLISECONDS.toDays(millionSeconds).toString() + "days"

如果要计算两天,请更改:

val millionSeconds = yourDate1.time - yourDate2.time

应该工作。

答案 5 :(得分:3)

java.time和ThreeTenABP

如果我的理解正确,那么您希望从开始日期到结束日期(包括该天)的天数。

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");

    String startDate = "2/3/2017";
    String endDate = "3/3/2017";

    LocalDate startDateValue = LocalDate.parse(startDate, dateFormatter);
    LocalDate endDateValue = LocalDate.parse(endDate, dateFormatter);
    long days = ChronoUnit.DAYS.between(startDateValue, endDateValue) + 1;

    System.out.println("Days: " + days);

输出:

天数:2

ChronoUnit.DAYS.between()为我们提供了从开始日期(包括开始日期)到结束日期(不包括日期)的天数。因此,也要包括结束日期,我们需要像问题中一样添加1天。

您的代码出了什么问题?

您正在使用Date(String)构造函数。自1997年以来,该构造函数已被弃用,因为它在各个时区均无法正常工作,因此请不要使用它。这也很神奇:至少我从来不真正知道自己能得到什么。显然,2/3/2017表示您打算在2017年2月3日到2017年3月2日。从2月3日到3月3日(包括首尾两天)为29天(因为2017年不是a年)。这说明了为什么要29岁。(如果需要,我们可以在文档中拼写方式,并找出为什么2/3/2017被这样解释,只有我发现这样做浪费了很多时间。)

您无法转换为毫秒。请注意,不仅是问题,而且从毫秒转换为天的很多答案都是错误的。这样的转换假定一天总是24小时。由于夏令时间(DST)和其他时间异常,一天并非总是24小时。例如,如果在夏季开始时假越过春季差距春季向前,那么所有这些答案都将算得很少。

问题:java.time是否不需要Android API级别26?

java.time在较新和较旧的Android设备上均可正常运行。它只需要至少 Java 6

  • 在Java 8和更高版本以及更新的Android设备(API级别26以上)中,内置了现代API。
  • 在非Android Java 6和7中,获得ThreeTen Backport,这是现代类的backport(JSR 310的ThreeTen;请参见底部的链接)。
  • 在旧版Android上,请使用Android版的ThreeTen Backport。称为ThreeTenABP。并确保使用子包从org.threeten.bp导入日期和时间类。

链接

答案 6 :(得分:2)

看看这段代码,这对我有帮助,希望它对你有帮助。

public String get_count_of_days(String Created_date_String, String Expire_date_String) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());

Date Created_convertedDate = null, Expire_CovertedDate = null, todayWithZeroTime = null;
try {
    Created_convertedDate = dateFormat.parse(Created_date_String);
    Expire_CovertedDate = dateFormat.parse(Expire_date_String);

    Date today = new Date();

    todayWithZeroTime = dateFormat.parse(dateFormat.format(today));
} catch (ParseException e) {
    e.printStackTrace();
}

int c_year = 0, c_month = 0, c_day = 0;

if (Created_convertedDate.after(todayWithZeroTime)) {
    Calendar c_cal = Calendar.getInstance();
    c_cal.setTime(Created_convertedDate);
    c_year = c_cal.get(Calendar.YEAR);
    c_month = c_cal.get(Calendar.MONTH);
    c_day = c_cal.get(Calendar.DAY_OF_MONTH);

} else {
    Calendar c_cal = Calendar.getInstance();
    c_cal.setTime(todayWithZeroTime);
    c_year = c_cal.get(Calendar.YEAR);
    c_month = c_cal.get(Calendar.MONTH);
    c_day = c_cal.get(Calendar.DAY_OF_MONTH);
}


/*Calendar today_cal = Calendar.getInstance();
int today_year = today_cal.get(Calendar.YEAR);
int today = today_cal.get(Calendar.MONTH);
int today_day = today_cal.get(Calendar.DAY_OF_MONTH);
*/

Calendar e_cal = Calendar.getInstance();
e_cal.setTime(Expire_CovertedDate);

int e_year = e_cal.get(Calendar.YEAR);
int e_month = e_cal.get(Calendar.MONTH);
int e_day = e_cal.get(Calendar.DAY_OF_MONTH);

Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();

date1.clear();
date1.set(c_year, c_month, c_day);
date2.clear();
date2.set(e_year, e_month, e_day);

long diff = date2.getTimeInMillis() - date1.getTimeInMillis();

float dayCount = (float) diff / (24 * 60 * 60 * 1000);

return ("" + (int) dayCount + " Days");

}

答案 7 :(得分:2)

非常简单,只需使用日历,为两个日期创建两个实例,转换为毫秒,减去并转换为天数(向上舍入)......像这样,基本上:

Calendar startDate = Calendar.getInstance();
startDate.set(mStartYear, mStartMonth, mStartDay);
long startDateMillis = startDate.getTimeInMillis();

Calendar endDate = Calendar.getInstance();
endDate.set(mEndYear, mEndMonth, mEndDay);
long endDateMillis = endDate.getTimeInMillis();

long differenceMillis = endDateMillis - startDateMillis;
int daysDifference = (int) (differenceMillis / (1000 * 60 * 60 * 24));

答案 8 :(得分:1)

如果您想使用收到的整数,请小心谨慎,例如指示自定义日历实现中的特定日期。例如,我尝试通过计算从1970-01-01到所选日期的日期,从每月日历视图进入每日视图并显示每日内容,并且每月25-31天显示我为一天前,因为datesDifferenceInMillis / (24 * 60 * 60 * 1000);可能会返回类似17645,95833333333的内容,并将其转换为int,您将获得较低的值1.在这种情况下,您可以通过使用NumberFormat舍入收到的浮点数来获得正确的天数类。这是我的代码:

NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
numberFormat.setMaximumFractionDigits(0);
numberFormat.setMinimumFractionDigits(0);
int days = numberFormat.parse(numberFormat.format(value)).intValue();

我希望它会有所帮助。

答案 9 :(得分:1)

超级简单

在android中使用ssh-keygen -t rsa ...包含LocalDate()

示例

在科特林

implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'

更好

val daysDifferene = LocalDate.of(2017,3,3).toEpochDay() - LocalDate.of(2017,3,2) 类创建扩展函数

LocalDate

现在就说

private operator fun LocalDate.minus(other: LocalDate) = toEpochDay() - other.toEpochDay()
  

在 Java 中

val daysDifference = localDate1 - localDate2 // you get number of days in Long type

答案 10 :(得分:0)

我在Kotlin中修改了Jitendra的答案:

fun getDaysBetweenDates(firstDateValue: String, secondDateValue: String, format: String): String
{
    val sdf = SimpleDateFormat(format, Locale.getDefault())

    val firstDate = sdf.parse(firstDateValue)
    val secondDate = sdf.parse(secondDateValue)

    if (firstDate == null || secondDate == null)
        return 0.toString()

    return (((secondDate.time - firstDate.time) / (1000 * 60 * 60 * 24)) + 1).toString()
}

并称呼它

val days = getDaysBetweenDates("31-03-2020", "24-04-2020","dd-MM-yyyy")

答案 11 :(得分:0)

您可以使用joda时间,它是如此简单

double[] array = {1, Double.NaN, 3};
DoubleSummaryStatistics statistics = Arrays.stream(array).filter(Double::isFinite).summaryStatistics();
double average = statistics.getAverage(); // 2.0
double sum = statistics.getSum(); // 4.0

开始日期和结束日期毫秒,结果示例:“ 2年1个月...”

答案 12 :(得分:0)

fun countDaysBetweenTwoCalendar(calendarStart: Calendar, calendarEnd: Calendar) : Int{
    val millionSeconds = calendarEnd.timeInMillis - calendarStart.timeInMillis
    val days = TimeUnit.MILLISECONDS.toDays(millionSeconds) //this way not round number
    val daysRounded = (millionSeconds / (1000.0 * 60 * 60 * 24)).roundToInt()
    return daysRounded
}

答案 13 :(得分:0)

尽管这些都不适合我,但是这是一种非常简单的功能来实现代码的简单方法:

private long getDaysDifference(Date fromDate,Date toDate) {

    if(fromDate == null || toDate == null)
        return 0;


    int a = Integer.parseInt(DateFormat.format("dd",   fromDate)+"");
    int b = Integer.parseInt(DateFormat.format("dd",   toDate)+"");

    if ( b <= a){
        return Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH) + b - a;
    }
    return b - a;
}

享受

相关问题