Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last timestamp of current month in Android

I tried to get the last timestamp in a chosen month of the year on Android. So I found getActualMaximum() of a Calendar instance useful; but when I tried to figure out what is the last timestamp of August in 2016, I got a 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. I am taking the minimum day of the following month minus one day:

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... (Maybe I found a bug?)

like image 594
Lior Zamir Avatar asked Oct 18 '25 18:10

Lior Zamir


1 Answers

import java.util.Calendar;

public class test_cal {

    public static void main(String[] args) {
        System.out.println(getLastTimeStampOfCurrentMonth(Calendar.AUGUST, 2016));
    }
    public static long getLastTimeStampOfCurrentMonth(int month, int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year); // leap year 29 Feb ;)
        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();
    }
}
like image 183
Vyacheslav Avatar answered Oct 20 '25 07:10

Vyacheslav