Java String to Date addTimeToDate(String date, int value, String unit, String sFormat)

Here you can find the source of addTimeToDate(String date, int value, String unit, String sFormat)

Description

This method adds time to a given date.

License

Open Source License

Parameter

Parameter Description
date a date in the specified format (null or empty is current date)
value the number of units that will be added to date.
unit one of 'year', 'month', 'week', 'day', 'hour', 'minute', 'second'.
sFormat The format to use for the in/output

Return

A string representation of the date.

Declaration

public static String addTimeToDate(String date, int value, String unit,
        String sFormat) 

Method Source Code

//package com.java2s;
/**/* ww  w.  j a  v  a 2 s .c om*/
 * ? 2003 Cordys R&D B.V. All rights reserved. The computer program(s) is the proprietary information of Cordys R&D B.V. and
 * provided under the relevant License Agreement containing restrictions on use and disclosure. Use is subject to the License
 * Agreement.
 */

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    /**
     * This method adds time to a given date.
     * 
     * @param date a date in the specified format (null or empty is current date)
     * @param value the number of units that will be added to date.
     * @param unit one of 'year', 'month', 'week', 'day', 'hour', 'minute', 'second'.
     * @param sFormat The format to use for the in/output
     * @return A string representation of the date.
     */
    public static String addTimeToDate(String date, int value, String unit,
            String sFormat) {
        String sRealFormat = sFormat;

        if ((sRealFormat == null) || sRealFormat.equals("")) {
            sRealFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS";
        }

        SimpleDateFormat UTCFormat = new SimpleDateFormat(sRealFormat);

        Date dDate = new Date(); // current date

        if ((date != null) && (date.length() != 0)) {
            try {
                dDate = UTCFormat.parse(date);
            } catch (Exception e) {
                // ignore exceptions
            }
        }

        // set time in a default calendar.
        Calendar cal = Calendar.getInstance();
        cal.setTime(dDate);

        // parse unit: one of 'year', 'month', 'week', 'day', 'hour', 'minute', 'second'.
        int iUnit = -1;

        if (unit.equalsIgnoreCase("year")) {
            iUnit = Calendar.YEAR;
        } else if (unit.equalsIgnoreCase("month")) {
            iUnit = Calendar.MONTH;
        } else if (unit.equalsIgnoreCase("week")) {
            iUnit = Calendar.WEEK_OF_YEAR;
        } else if (unit.equalsIgnoreCase("day")) {
            iUnit = Calendar.DAY_OF_MONTH;
        } else if (unit.equalsIgnoreCase("hour")) {
            iUnit = Calendar.HOUR_OF_DAY;
        } else if (unit.equalsIgnoreCase("minute")) {
            iUnit = Calendar.MINUTE;
        } else if (unit.equalsIgnoreCase("second")) {
            iUnit = Calendar.SECOND;
        } else {
            throw new RuntimeException("Unknown unit: " + unit);
        }

        // add time to calendar
        cal.add(iUnit, value);

        // new calendar date
        Date newDate = cal.getTime();

        String sReturn = fixedDateFormat(UTCFormat, newDate);

        return sReturn;
    }

    /**
     * Formats the date with the given date format class. This method fixes milliseconds in the formated string. Milliseconds are
     * outputed with minimum of three digits and zeroes are appended the left (which is incorrect for more than three digits).
     * 
     * @param sdf Date format object to be used.
     * @param dDate Date to be formatted.
     * @return Formatted string.
     */
    private static String fixedDateFormat(SimpleDateFormat sdf, Date dDate) {
        String sFormat = sdf.toPattern();
        String sMillisPattern = sFormat.replaceFirst(".*[^S](S+).*", "$1");

        if (sMillisPattern.equals(sFormat)) {
            // No milliseconds defined.
            return sdf.format(dDate);
        }

        int iMillisDigits = sMillisPattern.length();

        if (iMillisDigits == 3) {
            // This is the default behaviour, so use the default implementation.
            return sdf.format(dDate);
        }

        FieldPosition fp = new FieldPosition(DateFormat.Field.MILLISECOND);
        StringBuffer sb = new StringBuffer(50);

        sdf.format(dDate, sb, fp);

        int iStart = fp.getBeginIndex();
        int iEnd = fp.getEndIndex();

        if ((iStart < 0) || (iEnd <= iStart) || (iEnd > sb.length())) {
            // Probably the field was not in the string.
            return sb.toString();
        }

        String sValue = sb.substring(iStart, iEnd);

        if (iMillisDigits < 3) {
            sValue = sValue.substring(0, iMillisDigits);
        } else {
            sValue = Integer.toString(Integer.parseInt(sValue));

            // When less that one 1000 millis, add the zeros to the beginning.
            // otherwise we change the actual value.
            while (sValue.length() < 3) {
                sValue = "0" + sValue;
            }

            // Add extra zeros to the end.
            while (sValue.length() < iMillisDigits) {
                sValue += "0";
            }
        }

        sb.replace(iStart, iEnd, sValue);

        return sb.toString();
    }
}

Related

  1. getStringToDate(String date, String format)
  2. getStringToDate(String date, String inputDateFormat)
  3. getStringToDate(String pValue, String pDateFormat)
  4. getStringToDate(String str)