package chengbaoDemo; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * SimpleDateFormat *它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期) * *可以化日历 * */ public class Test02 { public static void main(String[] args) { for (int i = 1; i <= 12; i++) { printOneMonth(2016, i); System.out.println("\n"); } } /** *打印每个月的样式表<br> *@param int year *@param int month *@param int month *@param boolean isSearch <br> * true 将要查找的天标记 * false 不标记 */ public static void printOneMonth(int year, int month, int day, boolean isSearch) { System.out.println(month + "月"); //将输入数字,字符串格式化 String dStr = String.format("%4d%02d%02d", year, month, day); //(1)格式化 DateFormat DateFormat df = new SimpleDateFormat("yyyyMMdd"); Date d = null; try { //将字符串解析为时间 d = df.parse(dStr); } catch (ParseException e) { e.printStackTrace(); } //(2)日期字段的含义Calendar Calendar c = new GregorianCalendar(); c.setTime(d); //获取所要查找的那一天 int srcDay = -1; if (isSearch) srcDay = c.get(Calendar.DAY_OF_MONTH); //本月总天数 int days = c.getActualMaximum(Calendar.DAY_OF_MONTH); //设置日期为1号 c.set(Calendar.DATE, 1); //获取1号是周几 int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); //打印表头 System.out.println("日\t一\t二\t三\t四\t五\t六"); //打印每月第一天前的空格 for (int i = 1; i < dayOfWeek; i++) { System.out.print("\t"); } //打印一个月的情况 for (int i = 1; i <= days; i++) { //标注所要查找的那天 if (srcDay == i) { System.out.print("#"); } dayOfWeek = c.get(Calendar.DAY_OF_WEEK); System.out.print(i + "\t"); //每到周六换行 if (dayOfWeek == 7) { System.out.println(); } c.add(Calendar.DATE, 1); } } /** *重载<br> *打印每个月的样式表<br> *@param int year *@param int month *@param int month *@param boolean isSearch <br> * false 不标记 */ public static void printOneMonth(int year, int month) { printOneMonth(year, month, 1, false); } }
时间: 2024-11-08 19:14:38