Java常用類之Date和DateFormat用法

來源:互聯網
上載者:User

標籤:

Java常用類之Date和DateFormat用法
---20150802

1.Date時間類(java.util.Date)

-->在標準Java類庫中包含一個Date類。它的對象表示一個特定的瞬間,精確到毫秒

-->Java中時間的表示說白了也是數字,是從:標準紀元1970.1.1 0點開始到某個時刻的毫秒數,類型為long。


此類學習之建議----看源碼


 代碼: MyFundamental.TestDate.DateDemo

package TestDate;import java.util.Date;//注意不要導成java.sql.Date;public class DateDemo {/* * 測試Date類的用法 */public static void main(String[] args) {Date d1 =new Date();System.out.println(d1.getTime());long t = System.currentTimeMillis();//獲得目前時間System.out.println(t);Date d2 = new Date(1000);System.out.println(d2.toGMTString()); //不建議使用該方法d2.setTime(123134124); //重新設定時間System.out.println(d2.getTime());//可以使用after()和before()方法來比較時間,還可以直接比較System.out.println(d1.getTime() < d2.getTime());}}



2.DateFormat 類(java.Text.DateFormat)

-->抽象類別 abstract

    不能new對象,有唯一子類SimpleDateFormat,可以new對象

  具體用法見代碼,格式很固定


此類學習之建議----記住固定格式


  代碼: MyFundamental.TestDate.DateFormatDemo


package TestDate;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateFormatDemo {/* * 測試時間日期格式轉換 */public static void main(String[] args) {//1.將時間對象按照指定格式轉化成字串//DateFormat df = new DateFormat(); //報錯,DateFormat是抽象類別,不能new對象DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date d1 = new Date(System.currentTimeMillis());String str = df1.format(d1); //將時間對象格式化,轉換成字串System.out.println(str);System.out.println("#########################");//2.將指定的字串轉換成時間對象String str2 = "2015-8-2";DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd"); //需與上面字串的格式對應Date d2;try {d2 = df2.parse(str2);System.out.println(d2);} catch (ParseException e) {e.printStackTrace();}}}


===================華麗的分割線=========================


總結:這兩個是常用的時間日期及格式常用的類,需多加練習,熟練掌握。




著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java常用類之Date和DateFormat用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.