简体   繁体   中英

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)

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

Use this method for get timestamp of last day of Current month...

 private long getLastTimeStampOfCurrentMonth() {
     Calendar calendar = Calendar.getInstance();
     // passing month-1 because 0-->jan, 1-->feb... 11-->dec
     calendar.set(Calendar.getInstance().get((Calendar.YEAR)), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), 1);
     calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
     Date date = calendar.getTime();
     return date.getTime();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM