1、正常獲取系統時間輸出格式:
java代碼:
System.out.println(new java.util.Date());
輸出:Wed Jul 18 17:08:58 CST 2018
2、修改其格式
(1)用toLocaleString()方法(已過時,不過好像還能用)
java代碼:
System.out.println(new java.util.Date().toLocaleString());
輸出:2018-7-18 17:08:58
(2)過時的toLocaleString()方法由DateFormat.format(Date date)取代
java代碼:
Date date=new Date(); DateFormat ddf=DateFormat.getDateInstance(); System.out.println("日期:"+ddf.format(date)); System.out.println("===================="); DateFormat dtf=DateFormat.getTimeInstance(); System.out.println("時間:"+dtf.format(date)); System.out.println("===================="); DateFormat ddtf=DateFormat.getDateTimeInstance(); System.out.println("日期時間:"+ddtf.format(date)); System.out.println("===================="); SimpleDateFormat sdf=(SimpleDateFormat)DateFormat.getDateTimeInstance(); System.out.println("日期時間:"+sdf.format(date)); System.out.println("====================");
//這種可以指定格式
SimpleDateFormat sy1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("日期時間:"+sy1.format(date));
輸出:
日期:2018-7-18
====================
時間:17:08:58
====================
日期時間:2018-7-18 17:08:58
====================
日期時間:2018-7-18 17:08:58
====================
日期時間:2018-7-18 17:08:58
本方法適用於Windows系統。