0

sorry if the title is confusing. Let me explain clearly. I need to play with days, months and years. In order to do this I use Calendar. Here is my code;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int dayStart=0,monthStart=0,yearStart=0,dayFinish=0,monthFinish=0,yearFinish=0;

            Calendar cal = (Calendar) Calendar.getInstance();

            cal.set(Calendar.MONTH,Calendar.MAY); //SET MONTH AS MAY
            cal.set(Calendar.DATE,1);
            cal.set(Calendar.YEAR,2018);

            monthStart=(cal.getCalendar.MONTH)+1);
            dayStart=cal.get(Calendar.DATE);
            yearStart=cal.get(Calendar.YEAR);

            System.out.println("STARTING DAY: "+dayStart+" STARTING MONTH: "+monthStart+" STARTING YEAR: "+yearStart);

            cal.add(Calendar.MONTH,6); //ADD 6 MONTHS

            monthFinish = (cal.get(Calendar.MONTH)+1);
            dayFinish = (cal.get(Calendar.DATE));
            yearFinish = (cal.get(Calendar.YEAR));

            System.out.println("FINISHING DAY: "+dayFinish+" FINISHNG MONTH: "+monthFinish+" FINISHING YEAR: "+yearFinish);
//WHAT I WANT IS printing out the days between 2 dates: 184
    }

First, I set the time: 1 5 2018, then I add 6 months and the time becomes 1 11 2018. I need to get day difference as 184 (If I set the month January, it should be 181) Is it possible to do it just converting the corresponding Calendar fields (date,month,year) to secs or milliseconds and subtract millisecond value of (1 5 2018) from the (1 11 2018) and convert back milliseconds to days? There are similar questions but I couldn't find the solution exactly in the way I want.

Serkan Tarakcı
  • 177
  • 2
  • 13

3 Answers3

2

java.time

    LocalDate start = LocalDate.of(2018, Month.MAY, 1);
    LocalDate finish = start.plusMonths(6);
    long daysBetween = ChronoUnit.DAYS.between(start, finish);
    System.out.format("Days between %s and %s: %d%n", start, finish, daysBetween);

IMHO it’s clear and it’s brief. And the bonus, it works correctly. Output is:

Days between 2018-05-01 and 2018-11-01: 184

The Calendar class has design problems and is now long outdated. So I recommend using java.time, the modern Java date and time API, instead. There is a way to have a Calendar count days correctly, but it’s more complicated than you would expect, and there is no reason why you should want to bother. Calculating the days from the milliseconds (which is shown in several answers on Stack Overflow, not only the other answer to this question) will sometime give the correct result, sometimes not. The two issues are: (1) Due to summer time (DST) and other discontinuities a day may be 23, 24 or 25 hours or some number between or even outside this interval. If a day in the interval is shorter than 24 hours, converting from the milliseconds will yield 1 day too little. (2) A Calendar (despite its name) also holds time of day. In your code it will hold the same time of day before and after you add 6 months. In other cases the different time of day may cause you to get 1 day too few, or in rare cases 1 day too many.

Question: Can I use java.time on Android?

Yes, java.time works nicely on Android devices. It just requires at least Java 6.

  • In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
  • On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

You can try the something similar to this should work for you

import java.util.*; 
import java.util.concurrent.TimeUnit;
public class Calendar1 { 
    public static void main(String args[]) 
    { 
        Calendar startDate = Calendar.getInstance(); 
        //Setting year, month and day
        startDate.set(2018, 5, 1);
        Calendar endDate = Calendar.getInstance(); 
        endDate.set(2018, 11, 1);
        long end = endDate.getTimeInMillis();
        long start = startDate.getTimeInMillis();
        System.out.println("Time difference in days " + TimeUnit.MILLISECONDS.toDays(Math.abs(end - start)));

    } 
} 
Anuja Barve
  • 300
  • 1
  • 4
  • 23
1

Something this you can do. Change the year, Month and Date and set in the calendar. Use java.time.temporal.ChronoUnit to get the difference. The sample code is as below.

public void daysBetween() {

    Calendar startOfMonth = Calendar.getInstance();
    startOfMonth.set(Calendar.YEAR, 2018);
    startOfMonth.set(Calendar.MONTH, 10);
    startOfMonth.set(Calendar.DAY_OF_MONTH, 1);

    Calendar endOfMonth = Calendar.getInstance();
    endOfMonth.set(Calendar.YEAR, 2018);
    endOfMonth.set(Calendar.MONTH, 10);
    endOfMonth.set(Calendar.DAY_OF_MONTH, 30);

    System.out.println(ChronoUnit.DAYS.between(startOfMonth.toInstant(),endOfMonth.toInstant()));
}
  • Even if you cannot avoid getting a `Calendar` object, I agree with you that using `ChronoUnit.DAYS.between` is a good idea. Your code is incorrect, though. I used it for counting days between March 21 and 31, 2018. Do we agree that the expected result is 10? In my time zone (Europe/Copenhagen) I got 9. See my answer for an explanation or at least part of one. – Ole V.V. Nov 19 '18 at 11:29