Java Date Add addDate(String date1, String addpart, int num)

Here you can find the source of addDate(String date1, String addpart, int num)

Description

add Date

License

Open Source License

Declaration

public static String addDate(String date1, String addpart, int num) 

Method Source Code

//package com.java2s;
/*//from w ww  .j  a  v a 2  s.c o  m
 * Copyright 2010 Mttang.com All right reserved. This software is the
 * confidential and proprietary information of Mttang.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Mttang.com.
 */

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

public class Main {
    static final SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String addDate(String date1, String addpart, int num) {
        return addTime(date1, addpart, num).substring(0, 10);
    }

    public static String addTime(String time1, String addpart, int num) {
        try {
            String now = yyyyMMddHHmmss.format(new Date());
            time1 = (time1 == null) ? now : time1;
            if (time1.length() < 19) {
                time1 += " 00:00:00";
            }
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(yyyyMMddHHmmss.parse(time1));
            if (addpart.equalsIgnoreCase("Y")) {
                cal.add(Calendar.YEAR, num);
            } else if (addpart.equalsIgnoreCase("M")) {
                cal.add(Calendar.MONTH, num);
            } else if (addpart.equalsIgnoreCase("D")) {
                cal.add(Calendar.DATE, num);
            } else if (addpart.equalsIgnoreCase("H")) {
                cal.add(Calendar.HOUR, num);
            } else if (addpart.equalsIgnoreCase("F")) {
                cal.add(Calendar.MINUTE, num);
            } else if (addpart.equalsIgnoreCase("S")) {
                cal.add(Calendar.SECOND, num);
            }
            return yyyyMMddHHmmss.format(cal.getTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. addDate(int field, int amount)
  2. addDate(java.util.Date date, int day)
  3. addDate(String date)
  4. addDate(String date, int amount)
  5. addDate(String date, String type, int into)
  6. addDate(String dt, long day)
  7. addDateByDays(int days)
  8. addDateDay(int day)
  9. addDateParam(String dtstr, boolean start, List where)