1. 程式人生 > >CalendarPractice(面試題:如何根據給定的年份確定當年2月的天數)

CalendarPractice(面試題:如何根據給定的年份確定當年2月的天數)

package cn.itcast.api.a.map;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

public class DateAndCalendarPractice {

	public static void main(String[] args) throws ParseException{
//		練習一:將毫秒值轉成指定的日期格式
//		1.毫秒值time轉成date
		long time = System.currentTimeMillis();
		Date date = new Date(time);
//		2.通過日期時間格式器物件DateFormat對日起物件進行格式化(日期轉文字字串)
		DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
		String  str_time= format.format(date);
		System.out.println(str_time);
		
//		練習二:將2018-10-05轉成日期物件
		String str_date = "2018-10-05";
//		日期格式器
		DateFormat format1 = DateFormat.getDateInstance();//只能解析標準格式
		Date date2 = format1.parse(str_date);
		System.out.println(date2);
		
		
//		練習三:2018-10-05到2018年12月8號到底多少天
		/*字串不能相減但是毫秒值可以相減
		 * 
		 * 如何獲取毫秒值呢?
		 * 毫秒值->日期物件   日期物件 ->毫秒值
		 * 怎樣獲取日期物件?
		 * 字串文字->解析->日期物件
		 * 
		 * **/
		String str_date1 ="2018-10-05";
		String str_date2 ="2018年10月6日";
		//需要解析兩個模式的日期時間解析器 ,一個解析模式一一個解析模式二
		int style1 = DateFormat.MEDIUM;
		int style2 = DateFormat.LONG;
		int days = getDays(str_date1,str_date2 ,style1,style2);
	    System.out.println("days="+days);
	    System.out.println("--------------------");
	    
//	    獲取給定的年份的2月有多少天閏年判斷year %4==0&&year%100!=0||year%400==0
	    for(int year=2000;year<2021;year++)
	    {
	    	show(year);
	    }
	}
public static void show(int year){
//	   時間是連續的那麼我們只要找到當年3.1的前一天就可以知道當年的2月有多少天
	    Calendar c = Calendar.getInstance();
	    c.set(year, 2 ,1);
	    c.add(Calendar.DAY_OF_MONTH, -1);
	    int year1 = c.get(Calendar.YEAR);
	    int month = c.get(Calendar.MONTH)+1;
	    int day = c.get(Calendar.DAY_OF_MONTH);
	    String week = getCnWeek(c.get(Calendar.DAY_OF_WEEK));
	    System.out.println(year1+"年"+month+"月"+day+"日 "+week);
	
}
private static String getCnWeek(int i) {
		if(i<0||i>7)
		{
			throw new RuntimeException(i+"沒有對應的星期!");
		}
		String[] str = {"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
		
		return str[i];
	}	
	private static int getDays(String str_date1, String str_date2, int style1, int style2) throws ParseException{
//		1.根據給定的模式建立格式物件器
		DateFormat format2 = DateFormat.getDateInstance(style1);
		DateFormat format3 = DateFormat.getDateInstance(style2);
//		2.對文字進行解析
		Date date2 = format2.parse(str_date1);
		Date date3 = format3.parse(str_date2);
//		獲取日期的毫秒值
		long time1 = date2.getTime();
		long time2 = date3.getTime();
		long time = Math.abs(time2 - time1 ); 
//		將毫秒值轉化成天
		 int day = (int)(time/1000/60/60/24);
		
		
		return day;
		
		
	}

}