java 实现月历功能,输入年月日,得到月历

发布时间:2018-06-04作者:laosun阅读(4138)

java
    /**
    	 * 获取指定日期的月历
    	 * @author sun
    	 * @date 2018年5月7日 上午10:00:22
    	 * @param date
    	 */
    	public static void myCalendar(String yearMonth, Integer currentDay) {
    		int maxDay = 0;
    		int firstDay = 0;
    		if(currentDay==null){
    			currentDay = 0;
    		}
    		try {
    			DateFormat format = new SimpleDateFormat("yyyy-MM");
    			Date date = format.parse(yearMonth); // 将字符串转化为指定的日期格式
    			Calendar calendar = new GregorianCalendar();
    			calendar.setTime(date); // 将日期转化为日历
    			maxDay = calendar.getActualMaximum(Calendar.DATE); // 当前日期中当前月对应的最大天数
    			calendar.set(Calendar.DATE, 1); // 设置为当前月的第一天
    			firstDay = calendar.get(Calendar.DAY_OF_WEEK); // 当前日期中当前月第一天对应的星期数
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
    
    		System.out.println("日\t一\t二\t三\t四\t五\t六\n");
    		for (int j = 1; j < firstDay; j++) {
    			System.out.print("\t");
    		}
    
    		for (int i = 1; i <= maxDay; i++) {
    			if (i == currentDay) {
    				System.out.print("#");
    			}
    			System.out.print(i + "\t");
    			if ((i - (8 - firstDay)) % 7 == 0) {
    				System.out.println("\n");
    			}
    
    		}
    	}
    
    	public static void main(String[] args) {
    		myCalendar("2018-05", null);
    		myCalendar("2018-05", 7);
    	}


1 +1

版权声明

 Java  源码

 请文明留言

0 条评论