Java 获取上月年月字符串:简单高效的代码实现
Java 获取上月年月字符串:简单高效的代码实现
本文将介绍如何使用Java代码根据给定的年月字符串(例如 '202308')获取上月年月字符串。
代码实现
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String yearMonth = '202308';
String lastMonth = getLastMonth(yearMonth);
System.out.println('上月的年月为:' + lastMonth);
}
public static String getLastMonth(String yearMonth) {
SimpleDateFormat sdf = new SimpleDateFormat('yyyyMM');
try {
Date date = sdf.parse(yearMonth);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, -1);
return sdf.format(calendar.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
代码解释
-
getLastMonth(String yearMonth)方法:- 使用
SimpleDateFormat类将给定的年月字符串解析为Date对象。 - 使用
Calendar类获取当前日期,并将其设置为解析后的Date对象。 - 使用
calendar.add(Calendar.MONTH, -1)方法将日期减一个月。 - 使用
sdf.format(calendar.getTime())方法将日期格式化为年月字符串并返回。
- 使用
-
main方法:- 定义一个包含年月字符串的变量
yearMonth。 - 调用
getLastMonth方法获取上月年月字符串并将其存储在lastMonth变量中。 - 打印上月年月字符串。
- 定义一个包含年月字符串的变量
输出结果
上月的年月为:202307
总结
本文提供了一种简单高效的方法来获取给定年月字符串的上月年月字符串。该方法使用 SimpleDateFormat 和 Calendar 类,代码清晰易懂,易于理解和使用。
希望本文对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/qDw3 著作权归作者所有。请勿转载和采集!