Calendar類

Calendar類:是日曆類,有不少靜態方法。java

import java.util.Calendar;
import java.util.Date;
public class Calendardemo {
    public static void main(String[] args) {
        //Calendar類的方法getTime()
        Calendar c1 = Calendar.getInstance();//不須要直接new 子類的對象,經過靜態方法直接獲取
        Date date = c1.getTime();//把日曆對象,轉成Date日期對象
        System.out.println(date);
        
        Calendar c2 = Calendar.getInstance();
        c2.add(Calendar.DAY_OF_MONTH, -300);// 讓日曆中的天數向後偏移300天
        int year = c2.get(Calendar.YEAR);//
        int month = c2.get(Calendar.MONTH) + 1;//月,月份從零開始,因此月份要加1
        int day = c2.get(Calendar.DAY_OF_MONTH);//
        System.out.println(year + "" + month + "" + day + "");
        
        Calendar c3 = Calendar.getInstance();
        c3.set(2099, 4, 1);
        int year1 = c3.get(Calendar.YEAR);//
        int month1 = c3.get(Calendar.MONTH) + 1;//
        int day1 = c3.get(Calendar.DAY_OF_MONTH);//
        System.out.println(year1 + "" + month1 + "" + day1 + "");
        
        Calendar c4 = Calendar.getInstance();
        int year2 = c4.get(Calendar.YEAR);//
        int month2 = c4.get(Calendar.MONTH) + 1;//
        int day2 = c4.get(Calendar.DAY_OF_MONTH);//
        System.out.println(year2 + "" + month2 + "" + day2 + "");
        
        Calendar c5= Calendar.getInstance();
        System.out.println("年:" + c5.get(Calendar.YEAR));
        System.out.println("月:" + (c5.get(Calendar.MONTH) + 1));       
        System.out.println("日:" + c5.get(Calendar.DAY_OF_MONTH));
        System.out.println("時:" + c5.get(Calendar.HOUR_OF_DAY));
        System.out.println("分:" + c5.get(Calendar.MINUTE));
        System.out.println("秒:" + c5.get(Calendar.SECOND));
    }
}

相關文章
相關標籤/搜索