获取Android当前月份的上一个时间戳

时间:2016-09-08 12:04:23

标签: java android android-calendar

我试图在Android上找到当前一个月中的最后一个时间戳,所以我找到了

“calendar”实例的

getActualMaximum 很有用,但是当我试图找出2016年8月的最后一个时间戳时,我的错误天数是30而不是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();
}

当我采取下个月的最小值减1时,我找到了这种情况的解决方案:

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

我很好奇导致问题的原因......(我可能发现了一个错误)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

使用此方法获取当月最后一天的时间戳...

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