读书人

java中处置日期

发布时间: 2012-10-28 09:54:44 作者: rapoo

java中处理日期
Java中提供了丰富的日期表示方式。其中包—ate、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();//DateDate 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)));//TimestampTimestamp 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);//在月份上加1return cal.getTime();} //获取下一年的日期public Date nextYear(Date currentDate) {GregorianCalendar cal = new GregorianCalendar();cal.setTime(currentDate);cal.add(GregorianCalendar.YEAR, 1);//在年上加1return cal.getTime();}}本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/weoln/archive/2009/04/06/4051640.aspx

读书人网 >软件架构设计

热点推荐