資源描述:
《java日期函數(shù)》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在學(xué)術(shù)論文-天天文庫。
1、java中關(guān)于時(shí)間日期操作的常用函數(shù)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方法之前,必須先clear一下,否則很多信息會(huì)繼承自系統(tǒng)當(dāng)前時(shí)間2
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=newSimpleDateFormat("yyyy-MM
3、-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,8);cal.set(Calendar.DAY_OF_MONTH,3);intweekno=cal.get(Calendar.WEEK_OF_YEAR);(2)計(jì)算一年中的第幾星期是幾號(hào)Si
4、mpleDateFormatdf=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-025.add()和r
5、oll()的用法(1)add()方法SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-dd");Calendarcal=Calendar.getInstance();cal.set(Calendar.YEAR,2006);cal.set(Calendar.MONTH,8);cal.set(Calendar.DAY_OF_MONTH,3);cal.add(Calendar.DATE,-4);Datedate=cal.getTime();System.out.println
6、(df.format(date));cal.add(Calendar.DATE,4);date=cal.getTime();System.out.println(df.format(date));輸出:2006-08-302006-09-03(2)roll方法cal.set(Calendar.YEAR,2006);cal.set(Calendar.MONTH,8);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-09-292006-09-03可見,roll()方法在本月內(nèi)循環(huán),一般使用add()方法;6.計(jì)算兩個(gè)任意時(shí)間中間的間隔天數(shù)(1)傳進(jìn)Calendar對(duì)象/***//**計(jì)算兩個(gè)時(shí)間之間相隔天數(shù)*@paramstartday開始時(shí)間*@paramendday結(jié)束時(shí)
8、間*@return*/publicintgetIntervalDays(Calendarstartday,Calendarendday)...{//確保startday在endday之前if(startday.after(endday))...{Calendarcal=startday;startday=endday;endday=cal;}//分別得到兩個(gè)