Calendar類的小測試

2021-07-27 05:41:33 字數 1126 閱讀 5282

1.鍵盤錄入乙個年份,然後輸出該年二月份的天數。

scanner sc = new scanner(system.in);

system.out.println("請輸入乙個年份:");

int year = sc.nextint();

//建立日曆類

//static calendar getinstance() 使用預設時區和語言環境獲得乙個日曆。

calendar cs = calendar.getinstance();

//設定日曆,在指定的日曆下進行操作

cs.set(year, 2, 1); //這裡的2月實際上是3月,因為月從0開始

cs.add(calendar.day_of_month, -1); //對當前的日曆進行操作

int day=cs.get(calendar.day_of_month);

system.out.println(day);

sc.close();

2.日期和字串之間的轉換

//日期格式化字串

date d=new date();

system.out.println(d);

//******dateformat sdf=new ******dateformat();//預設格式

******dateformat sdf=new ******dateformat("yyyy-mm-dd hh:mm:ss");

string s=sdf.format(d);

下午5:37

system.out.println(s);//2017-02-20 17:40:03

//字串解析日期

string ss="2017-02-20 17:40:03";

******dateformat sd=new ******dateformat("yyyy-mm-dd hh:mm:ss");

//注意格式應該與給定的字串格式一樣

date dd=sd.parse(ss);

system.out.println(dd);

//mon feb 20 17:40:03 cst 2017

calendar 類的使用

下週,或者下個月 calendar calendar calendar.getinstance calendar.set calendar.year,2013 設定年份 calendar.set calendar.month,10 設定月份,顯示的比當前多乙個月 calendar.set calen...

常用類 Calendar類

calendar類概述及其方法 calendar 類是乙個抽象類,它為特定瞬間與一組諸如 year month day of month hour 等 日曆字段之間的轉換提供了一些方法,並為操作日曆字段 例如獲得下星期的日期 提供了一些方法。成員方法 public static calendar g...

日期操作類 Calendar類

calendar api 通過date和dateformat能夠格式化並建立乙個日期物件了,但是我們如何才能設定和獲取日期資料的特定部分呢,比如說小時,日,或者分鐘?我們又如何在日期的這些部分加上或者減去值呢?答案是使用calendar 類。calendar類的功能要比date類強大很多,而且在實現...