如何使用java中的Calendar類?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
日歷類,它是一個抽象類,封裝了所有的日歷字段值,通過統一的方法根據傳入不同的日歷字段可以獲取值。
1、得到一個日歷對象
Calendar c = Calendar.getInstance();//返回的是子類對象
2、成員方法
public void add(int field,int amount):根據給定的日歷字段和對應的時間,來對當前的日歷進行操作。 public final void set(int year,int month,int date):設置當前日歷的年月日
代碼實現:
import java.util.Calendar; /* * public void add(int field,int amount):根據給定的日歷字段和對應的時間,來對當前的日歷進行操作。 * public final void set(int year,int month,int date):設置當前日歷的年月日 */ public class CalendarDemo { public static void main(String[] args) { // 獲取當前的日歷時間 Calendar c = Calendar.getInstance(); // 獲取年 int year = c.get(Calendar.YEAR); // 獲取月 int month = c.get(Calendar.MONTH); // 獲取日 int date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // // 三年前的今天 // c.add(Calendar.YEAR, -3); // // 獲取年 // year = c.get(Calendar.YEAR); // // 獲取月 // month = c.get(Calendar.MONTH); // // 獲取日 // date = c.get(Calendar.DATE); // System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // 5年后的10天前 c.add(Calendar.YEAR, 5); c.add(Calendar.DATE, -10); // 獲取年 year = c.get(Calendar.YEAR); // 獲取月 month = c.get(Calendar.MONTH); // 獲取日 date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); System.out.println("--------------"); c.set(2011, 11, 11); // 獲取年 year = c.get(Calendar.YEAR); // 獲取月 month = c.get(Calendar.MONTH); // 獲取日 date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); } }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。