使用 Calendar 需要注意到的一點地方

2021-08-29 10:44:03 字數 1046 閱讀 8983

calendar cal=calendar.getinstance();

cal.set(integer.parseint("2007"), integer.parseint("11"),integer.parseint("08"));

system.out.println(cal.get(calendar.day_of_month));

system.out.println(cal.get(calendar.day_of_week));

上面的**可能會列印出和你所期望的不一樣:

這裡生成乙個cal1例項,這個例項的日期現在是當前日期。這是沒有錯的。

但下面cal.set(integer.parseint("2007"), integer.parseint("11"),integer.parseint("08"));

這種寫法:

我們重新設定了日期,但是當列印出星期資訊的時候,你會發現,星期資訊是原來的資訊,並沒有根據日期的變化而變化。

api上是這樣說的:

sets the values for the fields year, month, and date. previous values of other fields are retained. if this is not desired, callclearfirst.

意思就是,如果其餘的字段不需要需要保留,則首先呼叫clear方法。

試驗過,可以

或者使用下面的方式:

date date = format.parse( " 2007/12/08 " );

system.out.println(date.tostring());

calendar cal=calendar.getinstance();

cal .settime( date);

system.out.println(cal.get(calendar.day_of_month));

system.out.println(cal.get(calendar.day_of_week));

這樣一來就完全沒有問題了。

使用Calendar需要注意clear

date是前台傳的值,格式為2014 01 01的形式 如下的 是去date日期當月的最大天數日期 int month integer.parseint date.substring 5,7 取天數 int year integer.parseint date.substring 0,4 取年份 d...

ArrayList中儲存陣列時需要注意到的問題

因為陣列的位址是不會發生變化的,每次在陣列中的內容改變後,將陣列新增到arraylist中時,會導致arraylist中的每個內容都是最後新增進去的資料。案例如下所示 object objs new object count while rs.next al.add objs 假設rs中有20個資料...

shell指令碼要注意到的問題

1.指定bash shell 指令碼的第一行,之後應該是什麼?如果拿這個問題去問別人,不同的人的回答可能各不相同。我見過 usr bin env bash,也見過 bin bash,還有 usr bin bash,還有 bin sh,還有 usr bin env sh。這算是程式設計界的 茴 字四種...