Android calculate days between two dates

2020-03-01 07:17发布

I have written the following code to find days between two dates

    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);

When start and end date are 2/3/2017 and 3/3/2017 respectively the number of days showing is 29.Though when they are of the same day it is showing 1.(The number of days one takes a leave.So if one takes a single day leave,he has to select same start and end date.So in this case he has taken two days leave).

What am I doing wrong? Thank you for your time.

Note: Please don't use the date constructor. Check the accepted answer below. Use simpledateformat or Joda time. Date constructor is deprecated.

8条回答
家丑人穷心不美
2楼-- · 2020-03-01 07:39

What date format do you use? Is it d/M/yyyy or M/d/yyyy?

d = day, M = month, yyyy = year

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

Then the codes:

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;
}

And for getUnitBetweenDates method:

private static long getUnitBetweenDates(Date startDate, Date endDate, TimeUnit unit) {
    long timeDiff = endDate.getTime() - startDate.getTime();
    return unit.convert(timeDiff, TimeUnit.MILLISECONDS);
}
查看更多
劫难
3楼-- · 2020-03-01 07:40

Your code for generating date object:

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

You are getting 28 days as answer because according to Date(String) constructor it is thinking day = 3,month = 2 and year = 2017

You can convert String to Date as follows:

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

Use above template to make your Date object. Then use below code for calculating days in between two dates. Hope this clear the thing.

It can de done as follows:

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

Please check link

If you use Joda Time it is much more simple:

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

Please check JodaTime

How to use JodaTime in Java Project

查看更多
我想做一个坏孩纸
4楼-- · 2020-03-01 07:45

Does Android fully support java-8? If yes you can simple use 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

or same thing using formatter

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
查看更多
5楼-- · 2020-03-01 07:52

Be carefur if you'd like to use received integer e.g. to indicate specific day in custom calendar implementation. For example, I tried to go in m app from monthly calendar view to daily view and show daily content, by calculating dates from 1970-01-01 to selected one, and each 25-31th day of month shows me as one day earlier, because datesDifferenceInMillis / (24 * 60 * 60 * 1000); may return something like 17645,95833333333, and casting this to int you'll get value lower by 1. In this case correctly number of days you'll get by rounding received float by using NumberFormat class. Here's my code:

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();

I hope it will be helpful.

查看更多
Melony?
6楼-- · 2020-03-01 07:53

Kotlin

Here is the example to calculate days from today to some date:

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

If you want to calculate two days, then change:

val millionSeconds = yourDate1.time - yourDate2.time

should work.

查看更多
爷、活的狠高调
7楼-- · 2020-03-01 07:59

Very simple, just use Calendar, create two instances for the two dates, convert to milliseconds, subtract and convert to days (rounded up)... like this, basically:

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));
查看更多
登录 后发表回答