Java日期计算

 

Java中提供了丰富的日期表示方式。其中包括DateTimestampCalendar、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();

}

}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值