一、Calendar类获取上个月日期
Java中,使用Calendar
类的add
方法可以对日期进行加减操作。例如使用add(Calendar.MONTH, -1)
就可以获取上个月的日期了。
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
Date lastMonth = calendar.getTime();
上面的代码中,首先使用getInstance
方法获取一个Calendar
实例,然后使用add
方法将月份减去1,最后使用getTime
方法获取Date
对象,就可以得到上个月的日期了。
二、DateFormat格式化日期
得到Date
对象之后,我们通常需要将其转化成字符串格式的日期。Java中,使用DateFormat
类可以方便地对日期进行格式化。
Date lastMonth = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String lastMonthStr = dateFormat.format(lastMonth);
上面的代码中,首先使用SimpleDateFormat
指定日期格式,然后使用format
方法获取格式化后的日期字符串。
三、Joda-Time库获取上个月日期
Joda-Time是一个流行的Java日期/时间处理库,其提供了许多方便的日期操作方法。使用Joda-Time库可以更加方便地获取上个月的日期。
DateTime dateTime = new DateTime();
dateTime = dateTime.minusMonths(1);
String lastMonthStr = dateTime.toString("yyyy-MM-dd");
上面的代码中,首先使用DateTime
类获取当前日期时间,并使用minusMonths
方法将月份减去1,然后使用toString
方法以指定格式获取日期字符串。
四、Apache Commons Lang库获取上个月日期
Apache Commons Lang是一个常用的开源Java库,其提供了一些常用的工具类。使用该库,可以更加方便地获取上个月的日期。
Date lastMonth = DateUtils.addMonths(new Date(), -1);
String lastMonthStr = DateFormatUtils.format(lastMonth, "yyyy-MM-dd");
上面的代码中,首先使用DateUtils
类的addMonths
方法获取上个月的Date
对象,然后使用DateFormatUtils
类的format
方法将Date
对象转化为格式化后的字符串。