【需求】:获取年月日(格式:xxxx年xx月xx日)
【代码区域】
public static void main(String[] args){ Calendar cal = Calendar.getInstance(); int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); int day = cal.get(Calendar.DATE); String m = ""; if (month < 10) { m = "0" + month; } else { m = month + ""; } String d = ""; if (day < 10) { d = "0" + day; } else { d = day + ""; } System.out.println(year + m + d); }
【结果展示】
【需求】 :获取最近一年的年月(格式:xxxx年xx月)
【代码区域】
public static void main(String[] args){ Calendar cal = Calendar.getInstance(); int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); for (int i = 12; i > 0; i--) { if (month < 1) { year -= 1; month = 12; } String m = ""; if (month < 10) { m = "0" + month; } else { m = month + ""; } System.out.println(year + m); month--; } }
【结果展示】
【笔者小尾巴】
如果文章对你有用,可以动动小手给个小赞。如果有要改进地方,欢迎大侠评论~