Java SQL Date Add addDate(int add, java.util.Date d)

Here you can find the source of addDate(int add, java.util.Date d)

Description

add Date

License

Open Source License

Declaration

public static Date addDate(int add, java.util.Date d) 

Method Source Code


//package com.java2s;
import java.sql.Date;

import java.text.*;
import java.util.Calendar;

import java.util.TimeZone;

public class Main {
    public static final String DEFAULT_DATE_YMD_FORMAT = "yyyy-MM-dd";
    public static final String DEFAULT_CHAR_DATE_YMD_FORMAT = "yyyyMMdd";

    public static Date addDate(int add, java.util.Date d) {
        return addDate(add, new Date(d.getTime()));
    }//from w w  w  .  j av  a  2s . c  o  m

    public static Date addDate(int add, Date d) {

        if (d == null) {
            return null;
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime((java.util.Date) d);
        cal.setTimeZone(TimeZone.getDefault());
        cal.add(Calendar.DAY_OF_MONTH, add);

        return new Date(cal.getTime().getTime());
    }

    public static String addDate(int add, String sDate) {

        if (sDate.length() < 8) {
            return null;
        }

        return formatDate(addDate(add, formatCharDateYMD(sDate, DEFAULT_CHAR_DATE_YMD_FORMAT)),
                DEFAULT_CHAR_DATE_YMD_FORMAT);
    }

    public static String formatDate(java.util.Date value, String pattern) {
        TimeZone tz = TimeZone.getDefault();
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setTimeZone(tz);

        return sdf.format(value);
    }

    public static Date formatCharDateYMD(String str) {
        return formatCharDateYMD(str, DEFAULT_DATE_YMD_FORMAT);
    }

    public static Date formatCharDateYMD(String str, String format) {

        if (str == null || str.trim().length() == 0) {
            return null;
        }

        if (format == null) {
            throw new IllegalArgumentException("The value of an argument is inaccurate.");
        }

        SimpleDateFormat sdf = new SimpleDateFormat(format);

        ParsePosition pos = new ParsePosition(0);

        java.util.Date date = sdf.parse(str, pos);

        if (date == null) {
            return null;
        }
        return new Date(date.getTime());
    }

    public static Date formatCharDateYMD(String yy, String mm, String dd) {

        if (yy == null || mm == null || dd == null || yy.trim().length() == 0 || mm.trim().length() == 0
                || dd.trim().length() == 0) {
            return null;
        }
        return formatCharDateYMD(yy + "-" + (mm != null && mm.length() == 1 ? "0" + mm : mm) + "-"
                + (dd != null && dd.length() == 1 ? "0" + dd : dd));
    }
}

Related

  1. add(Date date, int unit, int amount)
  2. addDate(java.util.Date date, int day)
  3. addDate(String date)
  4. addDays(Date date, int days)
  5. addDaysToSQLDate(java.sql.Date date, int days)