Example usage for java.util GregorianCalendar add

List of usage examples for java.util GregorianCalendar add

Introduction

In this page you can find the example usage for java.util GregorianCalendar add.

Prototype

@Override
public void add(int field, int amount) 

Source Link

Document

Adds the specified (signed) amount of time to the given calendar field, based on the calendar's rules.

Usage

From source file:com.sammyun.util.DateUtil.java

/**
 * ??// w ww.  j a v a 2  s .c o m
 * 
 * @param inDate 
 * @param days ?
 * @return Date
 */
public static Date getDateByAddMonth(Date inDate, int month) {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(inDate);
    calendar.add(Calendar.MONTH, month);
    return calendar.getTime();
}

From source file:org.apache.oodt.cas.metadata.util.PathUtils.java

public static String doDynamicDateReplacement(String string, Metadata metadata)
        throws CasMetadataException, CommonsException {
    Pattern datePattern = Pattern.compile(
            "\\[\\s*DATE\\s*(?:[+-]{1}[^\\.]{1,}?){0,1}\\.\\s*(?:(?:DAY)|(?:MONTH)|(?:YEAR)|(?:UTC)|(?:TAI)){1}\\s*\\]");
    Matcher dateMatcher = datePattern.matcher(string);
    while (dateMatcher.find()) {
        String dateString = string.substring(dateMatcher.start(), dateMatcher.end());
        GregorianCalendar gc = new GregorianCalendar();

        // roll the date if roll days was specfied
        int plusMinusIndex;
        if ((plusMinusIndex = dateString.indexOf('-')) != -1
                || (plusMinusIndex = dateString.indexOf('+')) != -1) {
            int dotIndex;
            if ((dotIndex = dateString.indexOf('.', plusMinusIndex)) != -1) {
                int rollDays = Integer.parseInt(
                        PathUtils.replaceEnvVariables(dateString.substring(plusMinusIndex, dotIndex), metadata)
                                .replaceAll("[\\+\\s]", ""));
                gc.add(GregorianCalendar.DAY_OF_YEAR, rollDays);
            } else {
                throw new CasMetadataException(
                        "Malformed dynamic date replacement specified (no dot separator) - '" + dateString
                                + "'");
            }/*from w  w w .j a  v a2 s  .  co  m*/
        }

        // determine type and make the appropriate replacement
        String[] splitDate = dateString.split("\\.");
        if (splitDate.length < 2) {
            throw new CasMetadataException("No date type specified - '" + dateString + "'");
        }
        String dateType = splitDate[1].replaceAll("[\\[\\]\\s]", "");
        String replacement;
        if (dateType.equals("DAY")) {
            replacement = StringUtils.leftPad(gc.get(GregorianCalendar.DAY_OF_MONTH) + "", 2, "0");
        } else if (dateType.equals("MONTH")) {
            replacement = StringUtils.leftPad((gc.get(GregorianCalendar.MONTH) + 1) + "", 2, "0");
        } else if (dateType.equals("YEAR")) {
            replacement = gc.get(GregorianCalendar.YEAR) + "";
        } else if (dateType.equals("UTC")) {
            replacement = DateUtils.toString(DateUtils.toUtc(gc));
        } else if (dateType.equals("TAI")) {
            replacement = DateUtils.toString(DateUtils.toTai(gc));
        } else {
            throw new CasMetadataException("Invalid date type specified '" + dateString + "'");
        }

        string = StringUtils.replace(string, dateString, replacement);
        dateMatcher = datePattern.matcher(string);
    }
    return string;
}

From source file:org.squale.squalecommon.enterpriselayer.facade.component.AuditFacade.java

/**
 * Permet de reprogramm un audit sur une application au lendemain. si il s'agit d'un audit de suivi, l'audit dj
 * programm est supprim//from  w w  w .jav  a  2 s.  c  o m
 * 
 * @param pAudit AuditDTO dfinissant l'id de l'audit
 * @return l'audit reprogramm
 * @throws JrafEnterpriseException si erreur
 */
public static AuditDTO restartAudit(AuditDTO pAudit) throws JrafEnterpriseException {
    AuditDTO auditDTO = null;
    ISession session = null;
    try {
        // cration d'une session Hibernate
        session = PERSISTENTPROVIDER.getSession();
        AuditDAOImpl auditDAO = AuditDAOImpl.getInstance();
        // On rcupre l'audit dont l'id est renseign par pAudit
        AuditBO failedAudit = (AuditBO) auditDAO.load(session, new Long(pAudit.getID()));
        // On transforme le bo en dto
        auditDTO = AuditTransform.bo2Dto(failedAudit, pAudit.getApplicationId());
        // On change la date pour le lancer le lendemain  0:00
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(GregorianCalendar.HOUR_OF_DAY,
                ApplicationFacade.HOUR_OF_AUDIT - cal.get(GregorianCalendar.HOUR_OF_DAY));
        cal.add(GregorianCalendar.MINUTE,
                ApplicationFacade.MINUTE_OF_AUDIT - cal.get(GregorianCalendar.MINUTE));
        auditDTO.setDate(cal.getTime());
        // Son status sera en attente d'excution
        auditDTO.setStatus(AuditBO.NOT_ATTEMPTED);
        // On insre l'audit avec un traitement diffrent selon le type de l'audit
        if (auditDTO.getType().equals(AuditBO.MILESTONE)) {
            auditDTO = insertAudit(auditDTO);
        } else { // Il s'agit d'un audit de suivi
            auditDTO = restartNormalAudit(auditDTO);
        }
    } catch (JrafDaoException e) {
        FacadeHelper.convertException(e, AuditFacade.class.getName() + ".restartAudit");
    } finally {
        FacadeHelper.closeSession(session, AuditFacade.class.getName() + ".restartAudit");
    }
    return auditDTO;
}

From source file:com.sammyun.util.DateUtil.java

/**
 * beginDatedatas,datas?0??datasdatas0??datas
 * // w  w  w  .  j  av  a  2  s . co m
 * @param ?
 * @return 
 */
public static Date getDate(Date beginDate, int datas) {
    Calendar beginCal = Calendar.getInstance();
    beginCal.setTime(beginDate);
    GregorianCalendar calendar = new GregorianCalendar(beginCal.get(Calendar.YEAR),
            beginCal.get(Calendar.MONTH), beginCal.get(Calendar.DATE));
    calendar.add(GregorianCalendar.DATE, datas);
    String begin = new java.sql.Date(calendar.getTime().getTime()).toString();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date endDate = null;
    try {
        endDate = sdf.parse(begin);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return endDate;
}

From source file:org.sonar.plugins.dbcleaner.period.PeriodsTest.java

@Test
public void getDateShouldReturnCurrentTimeMinusDesiredMonths() {
    Project project = new Project("myproject");
    PropertiesConfiguration conf = new PropertiesConfiguration();
    conf.setProperty("KEY", "2");
    project.setConfiguration(conf);//from ww w .  j  ava2  s  .c  o  m

    Date date = Periods.getDate(conf, "KEY", "2");

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.add(GregorianCalendar.MONTH, -2);
    Date expectedDate = calendar.getTime();

    assertThat(date.getMonth(), is(expectedDate.getMonth()));
}

From source file:de.escoand.readdaily.EndlessContentPager.java

private Date getDateOfPosition(final int position) {
    final GregorianCalendar calendar = new GregorianCalendar();
    calendar.add(Calendar.DATE, position - POSITIONS_INTIAL);
    return calendar.getTime();
}

From source file:org.openvpms.archetype.util.DateRulesTestCase.java

/**
 * Tests the {@link DateRules#getTomorrow()} method.
 *///from  ww  w . j a  v  a2  s .c om
@Test
public void testGetTomorrow() {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(new Date());
    calendar.add(Calendar.DAY_OF_MONTH, 1);

    Date expected = DateUtils.truncate(calendar.getTime(), Calendar.DAY_OF_MONTH);
    assertEquals(expected, DateRules.getTomorrow());
}

From source file:org.eurekastreams.server.action.execution.notification.DeleteOldApplicationAlertsExecution.java

/**
 * {@inheritDoc} This method calls the database mapper to delete application alerts that are older than ageInDays.
 * Before the delete, a mapper call is made to find which users had old unread alerts then after the actual
 * deletion, the cached count of unread alerts for these users is synced with the database.
 *///  w  ww .j a  v  a  2 s.  co  m
@Override
public Serializable execute(final ActionContext inActionContext) {
    if (log.isInfoEnabled()) {
        log.info("Deleting application alerts older than " + ageInDays + " days");
    }

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.add(GregorianCalendar.DATE, ageInDays * -1);
    Date oldDate = calendar.getTime();

    List<Long> userIdsToSync = unreadMapper.execute(oldDate);

    deleteMapper.execute(oldDate);

    for (long userId : userIdsToSync) {
        syncMapper.execute(userId);
    }

    return true;
}

From source file:airport.services.dispatcher.GeneratorFlightImpl.java

private void createNewJobAndTrigger() {
    JobDataMap dataMap = new JobDataMap();

    dataMap.put(PARAMETER_FMTDAO_NAME, flyingMachineTypeDao);
    dataMap.put(PARAMETER_GENFLIGHTJMS_NAME, jMS);

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.add(GregorianCalendar.SECOND, DELAY_TIMER_SEC);

    jobDetailFlight = newJob(JobAddFlight.class).withIdentity(SCHEDULE_JOBDET_NAME, SCHEDULE_GROUP_NAME)
            .setJobData(dataMap).build();

    triggerFlight = newTrigger().withIdentity(SCHEDULE_TRIGGER_NAME, SCHEDULE_GROUP_NAME)
            .startAt(calendar.getTime()).withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(DELAY_TIMER_SEC).repeatForever())
            .build();/*from   www  .jav a 2 s.  c  o m*/
}

From source file:launcher.multithread.Extract.java

/**
 * Starts/*from  www  .  ja  va 2 s.c om*/
 */
protected void go() {
    GenericObjectPool pool = new GenericObjectPool(new ExtractorFactory());
    pool.setMaxActive(15);
    // wait forever
    pool.setMaxWait(-1);

    // hacktastic ;o)
    /*
    int[] rapIds = {218,67,92,26,497,374,1858,1039,429,716};      
    for(int i=0; i<rapIds.length; i++) {
       int rapId = rapIds[i];
    */
    for (int rapId = 0; rapId < 2000; rapId++) {

        // these have been done... 
        if (rapId == 218 || rapId == 67 || rapId == 92 || rapId == 26 || rapId == 497 || rapId == 374
                || rapId == 1858 || rapId == 1039 || rapId == 429 || rapId == 716) {
            continue;
        }

        logger.info("Queing up Id: " + rapId);
        SequenceProcessor workflow = (SequenceProcessor) context.getBean("GBIF:INDEX:1.0:extractOccurrence");
        Map<String, Object> seed = new HashMap<String, Object>();
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.MONTH, -6);
        seed.put("pageFrom", cal.getTime());
        seed.put("resourceAccessPointId", new Long(rapId));
        Thread t = new Thread(new Runner(seed, workflow, pool));
        t.start();
    }
}