1. System.currentTimeMillis()方法
可以獲取當前時間距離1970年01月01日00時00分00秒的秒數(shù),如果程序運行在北京時區(qū),則獲取的數(shù)據(jù)是當前時間距離1970年01月01日08時00分00秒的秒數(shù).
例如
System.out.PRintln(System.currentTimeMillis());
2. Date類
利用Date類獲取當前日期時間的方法如下
//打印當前時間 //方法一 System.out.println(new Date()); //方法二 System.out.println(new Date(System.currentTimeMillis()));可以利用字符串的split()方法將上述結果分割,獲得其中某個項的信息
Date date = new Date(); String []Word = date.toString().split(" ");//轉(zhuǎn)成字符串并且分割 for(String w:word) System.out.println(w);3. Calendar類
①獲取Calendar對象
利用Calendar的靜態(tài)方法getInstance()方法獲取Calendar對象.
②set方法
setTime(Date date)將日歷翻到date所在的時間.
set(int year,int month,int day)將日歷翻到y(tǒng)earmonth day對應的年月日.
③get方法
get(常量)根據(jù)常量為YEAR,MONTH_OF_YEAR等值獲取當前Calendar對象對應的年或月等單個信息.
例如
import java.util.Calendar;import java.util.Date;import static java.util.Calendar.*;public class AsMain { public static void main(String args[]){ Calendar calendar = Calendar.getInstance();//獲取Calendar對象 //1.獲取單個信息并分別打印 calendar.setTime(new Date(1000000000));//設置為當前日期 int year = calendar.get(YEAR);//獲取[年] int month = calendar.get(MONTH)+1;//注意:月份對應的數(shù)字比實際月份少 1 int day = calendar.get(DAY_OF_MONTH); int weekday = calendar.get(DAY_OF_WEEK); int hour = calendar.get(HOUR_OF_DAY); int minute = calendar.get(MINUTE); int second = calendar.get(SECOND);//獲取[秒0] System.out.println(year+"年"+month+"月"+day+"日"+ Weekday(weekday)+hour+"時"+minute+"分"+second+"秒"); //2.計算日期1和日期2的間隔天數(shù) year = 1987; month = 6; day = 5; calendar.set(year,month,day);//設定日期1 long totalsecond_1 = calendar.getTimeInMillis();//獲取日期1距離元年的秒數(shù) System.out.print(year+"年"+month+"月"+"日與"); year = 1987; month = 7; day = 9; calendar.set(year,month,day);//設置日期2 long totalsecond_2 = calendar.getTimeInMillis();//獲取日期2距離元年的秒數(shù) long days = (totalsecond_2 - totalsecond_1) / (24*3600*1000);//計算秒數(shù)之差,并換算成天數(shù) System.out.println(year+"年"+month+"月"+"日相隔"+days+"天"); } public static String Weekday(int weekday){ switch(weekday){ case 1:return "星期日"; case 2:return "星期一"; case 3:return "星期二"; case 4:return "星期三"; case 5:return "星期四"; case 6:return "星期五"; case 7:return "星期六"; default:return ""; } }}運行結果如下
1970年1月12日星期一21時46分40秒1987年6月日與1987年7月日相隔35天
新聞熱點
疑難解答