Java日期添加天数,减去天数,日历

时间:2020-02-23 14:34:26  来源:igfitidea点击:

有时在处理Java Date时,我们需要从中添加或者减去几天。
其中我提供了一个Java示例来向Java日期添加天数或者向Java日期对象减去天数。

Java日期添加天和减去天

下面是一个简单的Java Date加减天数示例程序。

package com.theitroad.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class JavaDateAddSubtract {

	public static void main(String[] args) {
		Date date = new Date();
		System.out.println("Today's date: "+date.toString());
		//test addDays method
		int i=10;
		while(i<=50){
			Date newDate = addDays(date, i);
			System.out.println("Java Date after adding "+i+" days: "+newDate.toString());
			i+=10;
		}
		System.out.println("\n\n");
		//test subtractDays method
		i=10;
		while(i<=50){
			Date newDate = subtractDays(date, i);
			System.out.println("Java Date after subtracting "+i+" days: "+newDate.toString());
			i+=10;
		}

	}
	/**
	 * add days to date in java
	 * @param date
	 * @param days
	 * @return
	 */
	public static Date addDays(Date date, int days) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.add(Calendar.DATE, days);
				
		return cal.getTime();
	}
	
	/**
	 * subtract days to date in java
	 * @param date
	 * @param days
	 * @return
	 */
	public static Date subtractDays(Date date, int days) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.add(Calendar.DATE, -days);
				
		return cal.getTime();
	}

}

上面程序的输出是:

Today's date: Thu Nov 15 11:45:05 PST 2012
Java Date after adding 10 days: Sun Nov 25 11:45:05 PST 2012
Java Date after adding 20 days: Wed Dec 05 11:45:05 PST 2012
Java Date after adding 30 days: Sat Dec 15 11:45:05 PST 2012
Java Date after adding 40 days: Tue Dec 25 11:45:05 PST 2012
Java Date after adding 50 days: Fri Jan 04 11:45:05 PST 2013

Java Date after subtracting 10 days: Mon Nov 05 11:45:05 PST 2012
Java Date after subtracting 20 days: Fri Oct 26 11:45:05 PDT 2012
Java Date after subtracting 30 days: Tue Oct 16 11:45:05 PDT 2012
Java Date after subtracting 40 days: Sat Oct 06 11:45:05 PDT 2012
Java Date after subtracting 50 days: Wed Sep 26 11:45:05 PDT 2012