Java學習:Date類、DateFomart類

來源:互聯網
上載者:User

標籤:pattern   日期時間   int   time   定義   F12   nbsp   final   構造   

Date類

 

Date:類 Date 表示特定的瞬間,精確到毫秒。

構造方法:
Date():預設擷取的是當前的日期時間
Date(long date):把當前日期按照指定的毫秒值進行設定

成員方法:
public long getTime():擷取日期對象的毫秒值
public void setTime(long time):設定日期對象的毫秒值

 1 //Date():預設擷取的是當前的日期時間 2         Date d = new Date(); 3         System.out.println(d); 4          5         //public long getTime():擷取日期對象的毫秒值 6         System.out.println(System.currentTimeMillis());//1492847203378 7         System.out.println(new Date().getTime()); 8          9         //Date(long date):把當前日期按照指定的毫秒值進行設定10         Date d2 = new Date(1492847203378L);11         System.out.println(d2);12         13         //public void setTime(long time):設定日期對象的毫秒值14         Date d3 = new Date();15         d3.setTime(1492847203378L);16         System.out.println(d3);
Date類示範

DateFomart類

 

格式化:
Date--String
2015年9月27日 15:14:23

String format(Date d)

解析:
String--Date
"2015-12-12"

Date parse(String s)


構造:
SimpleDateFormat()用預設的模式格式化日期對象
SimpleDateFormat(String pattern):用給定的模式格式化日期對象
例如:
yyyy年MM月dd日 HH:mm:ss
yyyy-MM-dd HH:mm:ss

成員方法:
public final String format(Date date)將一個 Date 格式化為日期/時間字串
public Date parse(String source)throws ParseException從給定字串的開始解析文本,以產生一個日期對象、

 

 1 //需求1:建立一個Date對象,格式化這個Date對象 2         //建立日期對象 3         Date d = new Date(); 4         //建立日期格式化對象,使用無參構造建立的日期格式化對象,格式化Date對象的時候,使用的是預設的格式 5         SimpleDateFormat sdf = new SimpleDateFormat(); 6         //調用他的format(Date d)格式化這個Date對象 7         String dateStr = sdf.format(d); 8         System.out.println(dateStr); 9         10         //需求:像自訂日期的格式化格式:2017-4-22  16:00:0011         //此時我們建立日期格式化對象的時候,就需要指定一個模式12         //2017-4-22  16:00:00對應的模式是:yyyy-MM-dd HH:mm:ss13         //重新建立一個日期的格式化對象,並指定相應的模式14         SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");15         String dateStr2 = sdf2.format(d);16         System.out.println(dateStr2);17         18         //yyyy年MM月dd日 HH:mm:ss做成這種模式的日期19         SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");20         String dateStr3 = sdf3.format(d);21         System.out.println(dateStr3);
代碼示範

 

Java學習:Date類、DateFomart類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.