Java基礎 與時間相關的類:System_Date_SimpleDateFormat_Calendar類
阿新 • • 發佈:2018-11-09
筆記總結:
/**與時間相關的類:System_Date_SimpleDateFormat_Calendar類 * 1.system 類下的currentTimeMillis() * 輸出從1970年至今的時間的毫秒數, 執行兩次即可用於統計時間間隔! * 2.Date() 類:java.util.Date : toString()/getTime()--返回long型64位整數 ; * 以及他的子類java.sql.Date * 3.SimpleDateFormat 類:(國際化) * 格式化: ①構造器: SimpleDateFormat() / SimpleDateFormat(String pattern) :常用pattern:"G yyyy:MM:dd 'at' HH:mm:ss " * ② String str=sdf.format(new Date()) : 利用sdf format一個Date()物件,格式化為字串輸出即可! * 解析: * ① 利用parse進行轉換, Date date1=sdf.parse("18-10-20 上午10:55"); * ② 直接輸出Date().toString() 顯示Date() 的標準時間! * 4.Calendar 類: * ① Calendar c=Calendar.getInstance(); //實現Calendar的引用,因為它沒有構造器 * ②get(field) / set(field,number) /add(field,number): number可以表示為正負數 * ③DAte getTime() /setTime()(Date d)*/
測試程式碼:
public class TestDate { @Test//1.Date類 public void test1(){ Date d1=new Date(); System.out.println(d1.toString()); System.out.println(d1.getTime());long x=d1.getTime(); Date d2=new Date(x); System.out.println(d2); } @Test//2.SimpleDateFormat public void test2() throws Exception{ //1.格式化1 SimpleDateFormat sdf=new SimpleDateFormat(); String str=sdf.format(new Date()); System.out.println(str); //18-10-20 上午10:55 //2.格式化2 SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss"); str=sdf1.format(new Date()); System.out.println(str); //2018:10:20 at 11:10:53 //3.解析 Date date1=sdf.parse("18-10-20 上午10:55"); System.out.println(date1); //Sat Oct 20 10:55:00 CST 2018 Date date2=sdf1.parse("2018-10-20 at 10:55:32"); System.out.println(date2); } @Test //3.Calendar() get public void test4(){ Calendar c=Calendar.getInstance(); //實現Calendar的引用 System.out.println("今天是本月的第幾天? "+c.get(Calendar.DAY_OF_MONTH)); System.out.println("今天的星期幾: "+(c.get(Calendar.DAY_OF_WEEK)-1) ); //列印當前時分秒 int h=c.get(Calendar.HOUR_OF_DAY); //不要用Calendar.HOUR,不然12點就成了0點 int m=c.get(Calendar.MINUTE); int s=c.get(Calendar.SECOND); System.out.println("當前Calendar的 時分秒: "+h+":"+m+":"+s); c.set(Calendar.DAY_OF_MONTH,23); Date d=c.getTime(); System.out.println("更新後的Date時間: "+d); } }
輸出結果:
Sat Oct 20 13:13:33 CST 2018 1540012413382 Sat Oct 20 13:13:33 CST 2018 18-10-20 下午1:13 2018-10-20 at 13:13:33 Sat Oct 20 10:55:00 CST 2018 Sat Oct 20 10:55:32 CST 2018 今天是本月的第幾天? 20 今天的星期幾: 6 當前Calendar的 時分秒: 13:13:33 更新後的Date時間: Tue Oct 23 13:13:33 CST 2018