開始使用new Date()測試,并用通過date.getMonth(),和date.getDay()獲取,不過后來發(fā)現(xiàn)這兩個訪求是jdk1.1版本的,現(xiàn)在已經(jīng)不用了,而且結(jié)果也不正確.
所以改用了Calendar
如下
Calendar rightNow = Calendar.getInstance();
int month =rightNow.MONTH;
int day = rightNow.DAY_OF_MONTH;
結(jié)果是month為2,而day為5,和現(xiàn)在的日期4.26沒有關(guān)系
我然后用System.out.println(rightNow);,不過輸出的很多內(nèi)容里面的MONTH和DAY_OF_MONTH是對的
后來,在網(wǎng)上查找,不能這么用
應(yīng)該用
int month = (date.get(Calendar.MONTH))+1;
int day = date.get(Calendar.DAY_OF_MONTH);
獲取當(dāng)前的月份和日期
試了一下,果然正確
后來查看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();
//當(dāng)前年
int year = cal.get(Calendar.YEAR);
//當(dāng)前月
int month = (cal.get(Calendar.MONTH))+1;
//當(dāng)前月的第幾天:即當(dāng)前日
int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
//當(dāng)前時:HOUR_OF_DAY-24小時制;HOUR-12小時制
int hour = cal.get(Calendar.HOUR_OF_DAY);
//當(dāng)前分
int minute = cal.get(Calendar.MINUTE);
//當(dāng)前秒
int second = cal.get(Calendar.SECOND);
//0-上午;1-下午
int ampm = cal.get(Calendar.AM_PM);
//當(dāng)前年的第幾周
int week_of_year = cal.get(Calendar.WEEK_OF_YEAR);
//當(dāng)前月的第幾周
int week_of_month = cal.get(Calendar.WEEK_OF_MONTH);
//當(dāng)前年的第幾天
int day_of_year = cal.get(Calendar.DAY_OF_YEAR);
|