Java日期計算

來源:互聯網
上載者:User

 

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();

}

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.