[19/03/16-星期六] 常用类_Date时间类DateFormat类
一、Date時間類
? ?計算機中 以1970 年 1 月 1 日 00:00:00定為基準時間,每個度量單位是毫秒(1秒的千分之一)
? ?用ong類型的變量來表示時間,如當前時刻數值:long? now =new System.currentTimeMillis();
【常用方法】
? ? ?1. Date() 分配一個Date對象,并初始化此對象為系統當前的日期和時間,可以精確到毫秒。
? ? ??2. Date(long date) 分配 Date 對象并初始化此對象,以表示自從標準基準時間(稱為“歷元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以來的指定毫秒數。
? ? ??3. boolean after(Date when)? 測試此日期是否在指定日期之后。
? ? ??4. booleanbefore(Date when)? 測試此日期是否在指定日期之前。
? ? ??5. boolean equals(Object obj)? ?比較兩個日期的相等性。
? ? ??6. long getTime() 返回自 1970 年 1 月 1 日 00:00:00 GMT 以來此 Date 對象表示的毫秒數。
? ? ??7. String toString() 把此 Date 對象轉換為以下形式的 String:?dow mon dd hh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun、 Mon、Tue、Wed、 Thu、 Fri、 Sat)。
【代碼示例】
1 /** 2 * 測試時間類 3 */ 4 package cn.sxt.test; 5 6 import java.util.Date; 7 public class Test_0316_DateClass { 8 public static void main(String[] args) { 9 Date date=new Date();//根據Java源碼可看出,如果這個構造Date類,什么參數都不傳,會輸出當前時刻的時間 10 System.out.println(date); 11 12 Date date2=new Date(2000); //這個Date類傳進去參數為2000(毫秒),會輸出從1970年1月1日00:00 起經過2000毫秒后的時刻 13 System.out.println(date2);//由于中國位于東八區 會在輸出時刻的基礎上加8個小時(此函數以格林威治時間為標準) 輸出8:00:02 14 15 System.out.println(date.getTime());//getTime()從基準時刻算起,獲得當前時刻的毫秒數 16 System.out.println(date2.getTime()); 17 18 System.out.println(date.after(date2));//判斷對象date時刻是否在對象date2時刻之后 19 System.out.println(date.before(date2));//判斷對象date時刻是否在對象date2時刻之前 20 21 } 22 23 24 }?
?二、DateFormat類?(時間格式化類)
? ? ?把時間對象轉化成指定格式的字符串。反之,把指定格式的字符串轉化成時間對象。
? ? ?DateFormat是一個抽象類,一般使用它的的子類SimpleDateFormat類來實現。
【代碼示例】
1 /* 2 *測試時間對象和字符串之間的相互轉化 3 * DateFormat類 時間格式類 是個抽象類 4 */ 5 package cn.sxt.test; 6 7 import java.text.DateFormat; 8 import java.text.ParseException; 9 import java.text.SimpleDateFormat; 10 import java.util.Date; 11 public class Test_0316_DateFormatClass { 12 public static void main(String[] args) throws ParseException { 13 14 //抽象類DateFormat不能通過new一個對象 而是通過實現類SimpleDateFormat來new 一個對象 15 16 //"把時間對象按照格式字符串輸出 " 格式化輸出日期 年(年是4位數字,用4個y)月(月2位,2個M)日(日2位,2個d) 以下同理 17 DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 18 DateFormat dFormat1 = new SimpleDateFormat("yyyy年MM月dd日 hh時mm分ss秒 ");//yyyy等是特殊標記不要變,其它自定義 19 20 String str=dFormat.format(new Date());//new Date() 當前時間的一個對象;dFormat.format()按照自定義的格式輸出當前時間 21 System.out.println(str); 22 System.out.println(dFormat1.format(new Date(4000)));//上面的更加縮寫版 表示按格式輸出4000毫秒后的時間 23 24 //把字符串轉成相應的時間對象輸出 25 26 String str1="2019-10-01 10:00:05";//字符串必須按照時間對象dFormat的("yyyy-MM-dd hh:mm:ss")格式書寫才會輸出 27 Date date = dFormat.parse(str1); 28 System.out.println(date); 29 30 //測試其它格式 31 DateFormat dFormat2 = new SimpleDateFormat("2019年第D天,當月的第d天,當月的第F星期,上/下午:a"); 32 System.out.println(dFormat2.format(date)); 33 34 36 } 37 38 39 }?
?
??
?
轉載于:https://www.cnblogs.com/ID-qingxin/p/10568005.html
總結
以上是生活随笔為你收集整理的[19/03/16-星期六] 常用类_Date时间类DateFormat类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BeanFactory和Applicat
- 下一篇: linux编辑文本内容的命令,Linux