Add an offset to a particular day - Java java.util

Java examples for java.util:Day

Description

Add an offset to a particular day

Demo Code


//package com.java2s;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Main {
    public static void main(String[] argv) throws Exception {
        Date when = new Date();
        int amount = 2;
        int field = 2;
        System.out.println(add(when, amount, field));
    }// w  ww.ja  va2 s .  c  om

    /**
     * Add an offset to a particular day
     * @param when the original date
     * @param amount the amount to add
     * @param field the field to add it to (from {@link java.util.Calendar}'s fields).
     * @return the date with the offset added
     */
    public static Date add(Date when, int amount, int field) {
        Calendar calendar = GregorianCalendar.getInstance(TimeZone
                .getTimeZone("UTC"));
        calendar.setTime(when);
        calendar.add(field, amount);
        return calendar.getTime();
    }
}

Related Tutorials