1、获取年份列表示例如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; public class Main { public static void main(String[] args) { String date1 = "2017-01-01"; String date2 = "2021-12-01"; DateFormat formater = new SimpleDateFormat("yyyy"); Calendar beginCalendar = Calendar.getInstance(); Calendar finishCalendar = Calendar.getInstance(); try { beginCalendar.setTime(formater.parse(date1)); finishCalendar.setTime(formater.parse(date2)); } catch (ParseException e) { e.printStackTrace(); } while (beginCalendar.before(finishCalendar) || beginCalendar.equals(finishCalendar)) { String date = formater.format(beginCalendar.getTime()).toUpperCase(); System.out.println(date); beginCalendar.add(Calendar.YEAR, 1); } } }View Code
2、获取月份列表示例如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; public class MainYearMonth { public static void main(String[] args) { String date1 = "2017-01-01"; String date2 = "2021-12-01"; //注意:这里的MM一定是大写,小写计算出的月份列表是错误的 DateFormat formater = new SimpleDateFormat("yyyy-MM"); Calendar beginCalendar = Calendar.getInstance(); Calendar finishCalendar = Calendar.getInstance(); try { beginCalendar.setTime(formater.parse(date1)); finishCalendar.setTime(formater.parse(date2)); } catch (ParseException e) { e.printStackTrace(); } while (beginCalendar.before(finishCalendar) || beginCalendar.equals(finishCalendar)) { String date = formater.format(beginCalendar.getTime()).toUpperCase(); System.out.println(date); beginCalendar.add(Calendar.MONTH, 1); } } }View Code
标签:年份,Java,String,beginCalendar,列表,finishCalendar,import,java,Calendar From: https://www.cnblogs.com/daytoy105/p/16654807.html