Java的Calendar類

來源:互聯網
上載者:User

標籤:sys   ati   ges   當前日期   時區   如何   time   UI   calendar類   

 

 

通過Date類我們可以建立並格式化一個日期對象,但是如何才能設定和擷取日期資料的特定部分呢?----Calendar類

Calendar類是一個抽象類別,在實際使用時實現特定的子類的對象,通過getInstance方法建立對象即可。

1、建立一個代表系統當前日期的Calendar對象。

Calendar c = Calendar.getInstance(); //預設是當前日期。

 

2、建立一個指定日期的Calendar對象。

  首先建立一個Calendar對象,然後再設定該對象中的年月日參數來完成。

Calendar cl = Calendar.getInstance();

cl.set(2009,6 - 1,12);//代表2009年6月12日

 

 

GregorianCalendar類

Calendar類實現了西曆日曆,GregorianCalendar是Calendar類的一個具體實現。

Calendar 的getInstance()方法返回一個預設用當前的語言環境和時區初始化的GregorianCalendar對象。GregorianCalendar定義了兩個欄位:AD和BC。這是代表西曆定義的兩個時代

package cuiyuee;import java.util.*;public class GregorianCalendarDemo {    public static void main(String[] args) {        // TODO Auto-generated method stub        String months[] = {                "Jan", "Feb", "Mar", "Apr",                  "May", "Jun", "Jul", "Aug",                  "Sep", "Oct", "Nov", "Dec"};                int year;        //初始化Gregorian日曆        //使用目前時間和日期        //預設為本地時間和時區        GregorianCalendar gcalendar = new GregorianCalendar();        System.out.println("Date:");        //顯示目前時間和日期的資訊        System.out.print(months[gcalendar.get(Calendar.MONTH)]);        System.out.print(" "+gcalendar.get(Calendar.DATE)+" ");        System.out.println(year = gcalendar.get(Calendar.YEAR));        System.out.print("Time:");        System.out.print(gcalendar.get(Calendar.HOUR)+":");        System.out.print(gcalendar.get(Calendar.MINUTE)+":");        System.out.println(gcalendar.get(Calendar.SECOND));                //測試當前年份是否為閏年        if(gcalendar.isLeapYear(year)){            System.out.println("當前年份是閏年");        }else{            System.out.println("當前年份不是閏年");        }            }}

 

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.