Java基礎複習:日期與時間

來源:互聯網
上載者:User

首先通過一個例子來簡單回顧Java中與日期和時間相關的類:

package day7;import java.text.SimpleDateFormat;import java.util.Date;/** * Date類:處理日期,時間,該類中的大部分方法已經過時,不推薦使用 * 從 JDK 1.1 開始,應該使用 Calendar 類實現日期和時間欄位之間轉換 * 使用 DateFormat 類來格式化和解析日期文字 * 常用構造方法:Date()分配 Date 對象並初始化此對象,以表示分配它的時間(精確到毫秒) *  * 未過時的方法: * boolean after(Date when) 測試此日期是否在指定日期之後 * boolean before(Date when)測試此日期是否在指定日期之前 */public class DateDemo {public static void main(String[] args) {//從1970年1月1日,00:00開始到現在的毫秒數System.out.println(System.currentTimeMillis());//1368598309172Date date = new Date();System.out.println(date);//Wed May 15 14:13:08 CST 2013/* * 但是這種日期格式並不符合我們的使用習慣,如何顯示為 2013-05-15 14:13:08 周一 * 我們可以使用java.text.SimpleDateFormat用來格式化日期 * SimpleDateFormat 是一個以與語言環境有關的方式來格式化和解析日期的具體類 * 它允許進行格式化(日期 -> 文本)、解析(文本 -> 日期)和正常化 */SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d HH:mm:ss E");//將日期格式使用指定的模式格式化為字串//date --> stringString dd = sdf.format(date);System.out.println(dd);//2013-5-15 14:19:53 星期三/* * 解析日期文字:String時間 --> Date *  Date parse(String text) 解析字串的文本,產生 Date。  */}}

 

練習題:寫兩個方法

1)按某種時間格式來輸出指定的String類型的時間(使用format)

2)把某種時間格式的String時間轉成Date類型時間(使用parse)

package day7;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateTestDemo {public static void main(String[] args) {Date date = new Date();String str = dateToString(date);System.out.println(str);//2013-05-15 14:34:50 星期三String str1 = "2013-05-20";Date date2 = stringToDate(str1);System.out.println(date2);}/** * 按"2010-01-01 12:00:20  星期一"的時間格式來輸出指定的String類型時間 * @param date 傳入Date對象 * @return 返迴轉換後的字串 */public static String dateToString(Date date){SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");String str = sdf.format(date);return str;}public static Date stringToDate(String str){SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Date date = null;try {date = sdf.parse(str);return date;} catch (ParseException e) {e.printStackTrace();}return null;}}

 常用的日期模式字母:

y:年

M:月

d:月中的天數

D:年中的天數

E:星期中的天數

H:時

m:分

s:秒

聯繫我們

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