java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java获取上一个月月份

Java 获取上一个月的月份的正确写法

作者:Best_Liu~

这篇文章主要介绍了java获取上一个月月份,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

Java 获取上一个月的月份的正确写法

 因最近在写代码的时候遇到了获取上个月月份的问题yyyy-MM这个格式,根据给的工具类,获取出来的值是有问题的,所以记录以下。

问题方法

         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        System.out.println(nowSdf.format(date));
        Calendar calendar = Calendar.getInstance();
        // 设置为当前时间
        calendar.setTime(date);
        // 设置为上一个月
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        date = calendar.getTime();

 正确的方法

 
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        System.out.println(nowSdf.format(date));
        Calendar calendar = Calendar.getInstance();
        // 设置为当前时间
        calendar.setTime(date);
        // 设置为上一个月
        //calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        calendar.add(Calendar.MONTH,-1);
        date = calendar.getTime();

java 由当前当前月得到上一个月

 SimpleDateFormat  sd=new    SimpleDateFormat("yyyy-MM");
        try {
            String payoffYearMonth = "2018-06";
            Date  currdate = sd.parse(payoffYearMonth);
            Calendar   calendar= Calendar.getInstance();
            calendar.setTime(currdate);
            calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)-1);
            System.out.println(sd.format(calendar.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }

到此这篇关于Java 获取上一个月的月份的文章就介绍到这了,更多相关java获取上一个月月份内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文