如何在java中获取上个月的日期和年份

时间:2015-11-25 05:59:34

标签: java calendar

首先我设定月份和年份,然后我想要上个月和年份不是当前月份。现在我只在那个月的日历上设定了哪个月

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class PrevMonth 
{
    private static String prev_day_str;
    private static String prev_month_str;

    public static void main(String[] args) 
    {
        SimpleDateFormat prev_day = new SimpleDateFormat("dd");
        Calendar calendar   = Calendar.getInstance();
        calendar.set(Calendar.MONTH, 1);
        calendar.set(Calendar.YEAR, 2015);

        calendar .add(Calendar.MONTH, -1);      //subtracting a month
        SimpleDateFormat prev_month = new SimpleDateFormat("MM");
        SimpleDateFormat prev_year = new SimpleDateFormat("YYYY");
        prev_day_str = prev_month.format(new Date(calendar .getTimeInMillis()));
        prev_month_str = prev_year.format(new Date(calendar .getTimeInMillis()));

        System.out.println(prev_day_str+" "+prev_month_str);
    }

}

结果: 2015年1月 需要12 2014年

2 个答案:

答案 0 :(得分:3)

您的代码:

calendar.set(Calendar.MONTH, 1);

实际上将月份设定为2月。

1月你需要使用0,即

calendar.set(Calendar.MONTH, 0);

答案 1 :(得分:0)

首先将日历初始化为二月而不是一月:

    public class PrevMonth  {
    private static String prev_day_str;
    private static String prev_month_str;

    public static void main(String[] args) 
    {
        SimpleDateFormat prev_day = new SimpleDateFormat("dd");
        Calendar calendar   = Calendar.getInstance();
        // 0 for January
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.YEAR, 2015);
        // -1 for substruct
        calendar .add(Calendar.MONTH, -1);      //subtracting a month
        SimpleDateFormat prev_month = new SimpleDateFormat("MM");
        SimpleDateFormat prev_year = new SimpleDateFormat("YYYY");
        prev_day_str = prev_month.format(new Date(calendar .getTimeInMillis()));
        prev_month_str = prev_year.format(new Date(calendar .getTimeInMillis()));

        System.out.println(prev_day_str+" "+prev_month_str);
    }

}