java获得上月日期问题Calendar类

 public static void main(String[] args) {
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.set(Calendar.MONTH, date.get(Calendar.MONTH) - 1);
        DateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String currYearMonth = sdf.format(date.getTime());
        System.out.println("currYearMonth : "+currYearMonth);

}

以上代码当windows 系统时间为2017年3月29日(3月28日之后4月之前)时,会出现获得上月为2017年3月,出现错误。在以windows 为服务器的web服务中已出现这个错误


于是找解决方法如下:

public static void main(String[] args) {
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.MONTH, -1);
        DateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String currYearMonth = sdf.format(date.getTime());
        System.out.println("currYearMonth : "+currYearMonth);
 }



猜你喜欢

转载自blog.csdn.net/u011630097/article/details/69666787