資源描述:
《常用的日期方法和屬性》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、常用的日期方法和屬性經(jīng)常用到時(shí)間日期類,所以就將常用的日期方法和屬性都?xì)w納總結(jié)如下,方便大家查找1.計(jì)算某一月份的最大天數(shù)Calendartime=Calendar.getInstance();time.clear();time.set(Calendar.YEAR,year);time.set(Calendar.MONTH,i-1);//注意,Calendar對(duì)象默認(rèn)一月為0intday=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天數(shù)注:在使用set方法之前,最好先
2、clear一下,否則很多信息會(huì)繼承自系統(tǒng)當(dāng)前時(shí)間2.Calendar和Date的轉(zhuǎn)化(1)Calendar轉(zhuǎn)化為DateCalendarcal=Calendar.getInstance();Datedate=cal.getTime();(2)Date轉(zhuǎn)化為CalendarDatedate=newDate();Calendarcal=Calendar.getInstance();cal.setTime(date);3.格式化輸出日期時(shí)間Datedate=newDate();SimpleDateFormatdf=newSimpl
3、eDateFormat("yyyy-MM-ddhh:mm:ss");System.out.println(df.format(date));4.計(jì)算一年中的第幾星期(1)計(jì)算某一天是一年中的第幾星期Calendarcal=Calendar.getInstance();cal.set(Calendar.YEAR,2006);cal.set(Calendar.MONTH,9);cal.set(Calendar.DAY_OF_MONTH,3);intweekno=cal.get(Calendar.WEEK_OF_YEAR);(2)
4、計(jì)算一年中的第幾星期是幾號(hào)SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-dd");Calendarcal=Calendar.getInstance();cal.set(Calendar.YEAR,2006);cal.set(Calendar.WEEK_OF_YEAR,1);cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);System.out.println(df.format(cal.getTime()));輸出:2006-01-0
5、25.add()和roll()的用法(1)add()方法SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-dd");Calendarcal=Calendar.getInstance();cal.set(Calendar.YEAR,2006);cal.set(Calendar.MONTH,9);cal.set(Calendar.DAY_OF_MONTH,3);cal.add(Calendar.DATE,-4);Datedate=cal.getTime();System.out.pr
6、intln(df.format(date));cal.add(Calendar.DATE,4);date=cal.getTime();System.out.println(df.format(date));輸出:2006-08-302006-10-03(2)roll方法cal.set(Calendar.YEAR,2006);cal.set(Calendar.MONTH,9);cal.set(Calendar.DAY_OF_MONTH,3);cal.roll(Calendar.DATE,-4);date=cal.getTime
7、();System.out.println(df.format(date));cal.roll(Calendar.DATE,4);date=cal.getTime();System.out.println(df.format(date));輸出:2006-10-292006-10-03可見(jiàn),roll()方法在本月內(nèi)循環(huán),一般使用add()方法;6.計(jì)算兩個(gè)任意時(shí)間中間的間隔天數(shù)(1)傳進(jìn)Calendar對(duì)象/***//**計(jì)算兩個(gè)時(shí)間之間相隔天數(shù)*@paramstartday開(kāi)始時(shí)間*@paramendday結(jié)束時(shí)間*@re
8、turn*/publicintgetIntervalDays(Calendarstartday,Calendarendday)...{//確保startday在endday之前if(startday.after(endday))...{Calendarcal=startday;startd