Lior Zamir Lior Zamir - 2 months ago 10
Java Question

Get last timestamp of current month in Android

I tried to get the last timestamp in the current month of the year on Android so i found

getActualMaximum of "calendar" instance useful but when i tried to figure out what is the last timestamp of August at 2016 i got wrong number of days 30 instead of 31

public static long getLastTimeStampOfCurrentMonth(int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(year,month, cal.getActualMaximum(Calendar.DAY_OF_MONTH), 23,59,59);
return cal.getTimeInMillis();
}


I found a solution for this case when i took the minimum of the following month minus one:

public static long getLastTimeStampOfCurrentMonth(int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(year,month, cal.getActualMinimum(Calendar.DAY_OF_MONTH)-1, 23,59,59);
return cal.getTimeInMillis();
}


I am curious about what caused the problem... (May i found a bug)

Answer
import java.util.Calendar;


public class test_cal {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(getLastTimeStampOfCurrentMonth(Calendar.AUGUST,2016));
    }
    public static long getLastTimeStampOfCurrentMonth(int month, int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, month);
        cal.set(year,month, cal.getActualMaximum(Calendar.DAY_OF_MONTH), cal.getActualMaximum(Calendar.HOUR_OF_DAY),cal.getActualMaximum(Calendar.MINUTE),cal.getActualMaximum(Calendar.SECOND));
        cal.set(Calendar.MILLISECOND,cal.getActualMaximum(Calendar.MILLISECOND));
        return cal.getTimeInMillis();
    }
}