前段時間作了一個倒計時的功能,用到了Date,Calendar,SimpleDateFormat,對它們之間的關係模糊,因此在這進行整理,也增強本身對它們之間關係的認識,同時也方便下次使用:html
1,時間java
Date date = new Date(); //初始化時間(當前時間爲系統默認) //以毫秒的方式獲取時間 long times = date.getTime();//返回自 1970 年 1 月 1 日 00:00:00 GMT 以來此 Date 對象表示的毫秒數。 date.setTime(long times);//設置時間爲指定的long時間 Date date = new Date(times);//初始化時間(當前時間爲指定的時間)
2,時間Date和String之間的轉換:api
1 SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 2 //把時間轉換爲指定字符串格式 3 String time = simpledateformat.format(new Date()); 4 //把指定字符串格式轉換爲時間 5 Date date = simpledateformat.parse(time);
2,時間的獲取與加減:spa
Calendar calendar = new GregorianCalendar();
//返回一個表示此 時間值(從曆元至如今的毫秒偏移量)的 對象。
Date date = calendar.getTime();
int year = calendar.get(Calendar.YEAR); //獲取年; int month = calendar.get(Calendar.MONTH); //獲取月; int date = calendar.get(Calendar.DATE); //獲取天; int hour = calendar.get(Calendar.HOUR); //獲取小時; int minute = calendar.get(Calendar.MINUTE); //獲取分鐘; int second = calendar.get(Calendar.SECOND); //獲取秒鐘; int hour_of_day = calendar.get(Calendar.HOUR_OF_DAY); //第幾個小時, int day_of_month = calendar.get(Calendar.DAY_OF_MONTH); //這天,在一個月內是第幾天. int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); //這天,在一週內,是第幾天. int day_of_year = calendar.get(Calendar.DAY_OF_YEAR); //這天,在一年內,是第幾天。 int week_of_year = calendar.get(Calendar.WEEK_OF_YEAR); //這周,在一年內是第幾周; int week_of_month = calendar.get(Calendar.WEEK_OF_MONTH);//這周,在這個月是第幾周;以以星爲標準; int zone_offset = calendar.get(Calendar.ZONE_OFFSET); //獲取時區; int day_of_week_in_month = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH); //某月中第幾周,按這個月1號算,1號起就是第1周,8號起就是第2周。以月份天數爲標準 //設置月份05;表明日曆的月份6月,由於月份從0開始。 calendar.clear(); //注:在使用set方法以前,必須先clear一下,不然不少信息會繼承自系統當前時間 calendar.set(Calendar.MONTH, 05); //設置日曆的月份是6月 int months = calendar.get(Calendar.MONTH); System.out.println(months); //輸出05;(實際是6月) //設置日曆日期爲2011-07-24 09:59:50 calendar.set(2011, 06, 24, 9, 59, 50); String getDate = date_format.format(calendar.getTime()); System.out.println(getDate); //輸出2011-07-24 09:59:50; //設置日曆爲當前時間,也能夠是任意date值。 calendar.setTime(new Date()); //加減(年月日。。都同樣) calendarNew.add(Calendar.DATE, 1); //當前日期上加一天(明天) calendarNew.add(Calendar.DATE, -1); //當前日期上減一天(昨天) //比較日前大小; //getTimeInMillis() 返回此 Calendar 的時間值,以毫秒爲單位,long類型。 if(new Date().getTime() > calendar.getTimeInMillis()){ System.out.println("當前日期在後!"); }else{ System.out.println("當前日期在前!"); } // 建立一個 Calendar 用於比較時間 Calendar calendarNew = Calendar.getInstance(); // 設定爲 5 小時之前,後者大,顯示 -1 calendarNew.add(Calendar.HOUR, -5); System.out.println("時間比較:" + calendarNew.compareTo(calendar)); // 設定7小時之後,前者大,顯示 1 calendarNew.add(Calendar.HOUR, +7); System.out.println("時間比較:" + calendarNew.compareTo(calendar)); // 退回 2 小時,時間相同,顯示 0 calendarNew.add(Calendar.HOUR, -2); System.out.println("時間比較:" + calendarNew.compareTo(calendar)); CalendarDate