Java Calendar獲取時間的月和日
開始使用new Date()測試,并用通過date.getMonth(),和date.getDay()獲取,不過后來發現這兩個訪求是jdk1.1版本的,現在已經不用了,而且結果也不正確.
Calendar rightNow = Calendar.getInstance();
int month =rightNow.MONTH;
int day = rightNow.DAY_OF_MONTH;
結果是month為2,而day為5,和現在的日期4.26沒有關系
我然后用System.out.println(rightNow);,不過輸出的很多內容里面的MONTH和DAY_OF_MONTH是對的
后來,在網上查找,不能這么用
應該用
int month = (date.get(Calendar.MONTH))+1;
int day = date.get(Calendar.DAY_OF_MONTH);
獲取當前的月份和日期
試了一下,果然正確
后來查看java doc文檔,MONTH字段解釋如下
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year is JANUARY which is 0; the last depends on the number of months in a year.
這個字段的值只是說明get()的屬性字段值,來獲取month的
以下為獲取其它:
Calendar cal = Calendar.getInstance();
//當前年
int year = cal.get(Calendar.YEAR);
//當前月
int month = (cal.get(Calendar.MONTH))+1;
//當前月的第幾天:即當前日
int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
//當前時:HOUR_OF_DAY-24小時制;HOUR-12小時制
int hour = cal.get(Calendar.HOUR_OF_DAY);
//當前分
int minute = cal.get(Calendar.MINUTE);
//當前秒
int second = cal.get(Calendar.SECOND);
//0-上午;1-下午
int ampm = cal.get(Calendar.AM_PM);
//當前年的第幾周
int week_of_year = cal.get(Calendar.WEEK_OF_YEAR);
//當前月的第幾周
int week_of_month = cal.get(Calendar.WEEK_OF_MONTH);
//當前年的第幾天
int day_of_year = cal.get(Calendar.DAY_OF_YEAR);