Java中提供了豐富的日期表示方式。其中包括Date、Timestamp、Calendar、GregorianCalendar類。GregorianCalendar類中提供了用於計算日期的add()方法,可以很方便地計算若干年、月、日後的日期。
給個例子看看:
package testjava;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateTest {
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateTest test = new DateTest();
//Date
Date currentDate = new Date();
System.out.println("當前日期是:" + df.format(currentDate));
System.out.println("一周后的日期是:" + df.format(test.nextWeek(currentDate)));
System.out.println("一月後的日期是:" + df.format(test.nextMonth(currentDate)));
System.out.println("一年後的日期是:" + df.format(test.nextYear(currentDate)));
//Timestamp
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
System.out.println("當前日期是:" + df.format(currentTime));
System.out.println("一周后的日期是:" + df.format(test.nextWeek(currentTime)));
System.out.println("一月後的日期是:" + df.format(test.nextMonth(currentTime)));
System.out.println("一年後的日期是:" + df.format(test.nextYear(currentTime)));
//另一種計算方式,這種方式計算月和年的日期比較困難
Timestamp nextTime = new Timestamp(currentTime.getTime() + 7 * 24 * 60 * 60 * 1000);
System.out.println("當前日期是:" + df.format(currentTime));
System.out.println("一周后的日期是:" + df.format(nextTime));
}
//擷取下一周的日期
public Date nextWeek(Date currentDate) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(currentDate);
cal.add(GregorianCalendar.DATE, 7);//在日期上加7天
return cal.getTime();
}
//擷取本周日的日期
public Date getSunday(Date monday) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(monday);
cal.add(GregorianCalendar.DATE, 6);//在日期上加6天
return cal.getTime();
}
//擷取下一月的日期
public Date nextMonth(Date currentDate) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(currentDate);
cal.add(GregorianCalendar.MONTH, 1);//在月份上加1
return cal.getTime();
}
//擷取下一年的日期
public Date nextYear(Date currentDate) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(currentDate);
cal.add(GregorianCalendar.YEAR, 1);//在年上加1
return cal.getTime();
}
}