Java - Calendar類的使用

來源:互聯網
上載者:User

標籤:

今天在寫代碼時需要用到時間相關的類,一開始,資料庫中存的資料類型是timestamp的,所以在Java中就使用了

Timestamp類型,但當調用Timestamp類型的方法時發現,它的很多方法都是deprecated,並且運行結果與預期有所差異。

Eclipse的自動提示我使用Calendar類來代替Timestamp類的使用。

 1 private static void testCalendar() { 2         Timestamp ts = new Timestamp(System.currentTimeMillis()); 3         Calendar cal = Calendar.getInstance(); 4         cal.setTime(ts); 5  6         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 7         System.out.println(sdf.format(ts)); 8  9         Calendar cal2 = Calendar.getInstance();10         cal2.set(Calendar.YEAR, 2015);11         cal2.set(Calendar.MONTH, 2);12         System.out.println(cal2.getActualMaximum(Calendar.DAY_OF_MONTH));13         System.out.println(cal2.get(Calendar.YEAR) + "-"14                 + cal2.get(Calendar.MONTH) + "-"15                 + cal2.get(Calendar.DAY_OF_MONTH) + " " +16                 + cal2.get(Calendar.HOUR_OF_DAY) + ":"17                 + cal2.get(Calendar.MINUTE) + ":" 18                 + cal2.get(Calendar.SECOND));19     }

通過調用Calendar的static方法得到一個Calendar執行個體,並且使用java.util.Date類型來進行初始化,

java.sql.Timestamp類型是Date類的子類,因而可以使用它來進行初始化操作。

這裡有兩點需要注意

1. Calendar的Month是從0開始計數的,也就是說一月是0,二月是1,....,十二月是11;

2. 使用SimpleDateFormat時,格式化字串需要區分是12小時制還是24小時制

1 SimpleDateFormat twelvesSDF= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//12小時制  2 3 SimpleDateFormat TwentyfourSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小時制  

 

Java - Calendar類的使用

聯繫我們

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