Java Code Examples for com.ibm.icu.util.Calendar#add()

The following examples show how to use com.ibm.icu.util.Calendar#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BirtDateTime.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected Object getValue( Object[] args, IScriptFunctionContext context ) throws BirtException
{
	if ( existNullValue( args ) )
	{
		return null;
	}
	Calendar current;
	if ( args[0] instanceof Number )
	{
		current = getFiscalYearStateDate( context, args );
		// Month starts with 1
		current.add( Calendar.MONTH,
				( (Number) args[0] ).intValue( ) - 1 );
	}
	else
	{
		current = getCalendar( DataTypeUtil.toDate( args[0] ) );
		Calendar start = getFiscalYearStateDate( context, args );
		adjustFiscalMonth( current, start );
		// Do not exceed the max days of current month
		current.set( Calendar.DATE,
				Math.min( start.get( Calendar.DATE ),
						current.getActualMaximum( Calendar.DATE ) ) );
	}
	return current.getTime( );
}
 
Example 2
Source File: ServerHitBin.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
private static long getEvenStartingTime(long binLength) {
    // binLengths should be a divisable evenly into 1 hour
    long curTime = System.currentTimeMillis();

    // find the first previous millis that are even on the hour
    Calendar cal = Calendar.getInstance();

    cal.setTime(new Date(curTime));
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    while (cal.getTime().getTime() < (curTime - binLength)) {
        cal.add(Calendar.MILLISECOND, (int) binLength);
    }

    return cal.getTime().getTime();
}
 
Example 3
Source File: TemporalExpressions.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
@Override
public boolean includesDate(Calendar cal) {
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    if (hour == this.start || hour == this.end) {
        return true;
    }
    Calendar compareCal = (Calendar) cal.clone();
    compareCal.set(Calendar.HOUR_OF_DAY, this.start);
    while (compareCal.get(Calendar.HOUR_OF_DAY) != this.end) {
        if (compareCal.get(Calendar.HOUR_OF_DAY) == hour) {
            return true;
        }
        compareCal.add(Calendar.HOUR_OF_DAY, 1);
    }
    return false;
}
 
Example 4
Source File: DateTimeSpan.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param startDate
 *            A date object that represents the base date
 * @param hours
 *            The number of hours to add to the date
 * @param minutes
 *            The number of minutes to add to the date
 * @param seconds
 *            The number of seconds to add to the date
 * @return A date that results adding the hours, minutes, seconds to the
 *         start date.
 */
static Date addTime( Date startDate, int hours, int minutes,
		int seconds )
{
	Calendar startCal = Calendar.getInstance( );
	Date firstDate = startDate;
	startCal.setTime( firstDate );
	/*
	 * Add years first. Then, using the resulting date, add the months.
	 * Then, using the resulting date, add the days.
	 */
	startCal.add( Calendar.HOUR_OF_DAY, hours );
	startCal.add( Calendar.MINUTE, minutes );
	startCal.add( Calendar.SECOND, seconds );

	return startCal.getTime( );
}
 
Example 5
Source File: BirtDateTime.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected Object getValue( Object[] args, IScriptFunctionContext context ) throws BirtException
{
	if ( existNullValue( args ) )
	{
		return null;
	}
	Calendar current;
	if ( args[0] instanceof Number )
	{
		current = getFiscalYearStateDate( context, args );
		// Week starts with 1
		current.add( Calendar.WEEK_OF_YEAR,
				( (Number) args[0] ).intValue( ) - 1 );
	}
	else
	{
		current = getCalendar( DataTypeUtil.toDate( args[0] ) );
	}
	current.set( Calendar.DAY_OF_WEEK, current.getFirstDayOfWeek( ) );
	return current.getTime( );
}
 
Example 6
Source File: EntitySyncServices.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Clean EntitySyncRemove Info
 *@param dctx The DispatchContext that this service is operating in
 *@param context Map containing the input parameters
 *@return Map with the result of the service, the output parameters
 */
public static Map<String, Object> cleanSyncRemoveInfo(DispatchContext dctx, Map<String, ? extends Object> context) {
    Debug.logInfo("Running cleanSyncRemoveInfo", module);
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    try {
        // find the largest keepRemoveInfoHours value on an EntitySyncRemove and kill everything before that, if none found default to 10 days (240 hours)
        double keepRemoveInfoHours = 24;

        List<GenericValue> entitySyncRemoveList = EntityQuery.use(delegator).from("EntitySync").queryList();
        for (GenericValue entitySyncRemove: entitySyncRemoveList) {
            Double curKrih = entitySyncRemove.getDouble("keepRemoveInfoHours");
            if (curKrih != null) {
                double curKrihVal = curKrih;
                if (curKrihVal > keepRemoveInfoHours) {
                    keepRemoveInfoHours = curKrihVal;
                }
            }
        }


        int keepSeconds = (int) Math.floor(keepRemoveInfoHours * 3600);

        Calendar nowCal = Calendar.getInstance();
        nowCal.setTimeInMillis(System.currentTimeMillis());
        nowCal.add(Calendar.SECOND, -keepSeconds);
        Timestamp keepAfterStamp = new Timestamp(nowCal.getTimeInMillis());

        int numRemoved = delegator.removeByCondition("EntitySyncRemove", EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.LESS_THAN, keepAfterStamp));
        Debug.logInfo("In cleanSyncRemoveInfo removed [" + numRemoved + "] values with TX timestamp before [" + keepAfterStamp + "]", module);

        return ServiceUtil.returnSuccess();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error cleaning out EntitySyncRemove info: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorCleaningEntitySyncRemove", UtilMisc.toMap("errorString", e.toString()), locale));
    }
}
 
Example 7
Source File: BirtDateTime.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add num years
 *
 * @param date
 * @param num
 * @return
 */
private static Date addYear( Date date, int num )
{
	Calendar startCal = getCalendar( date );

	startCal.add( Calendar.YEAR, num );

	return startCal.getTime( );
}
 
Example 8
Source File: TimeDuration.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/** Add this time duration to a Calendar instance. Returns the original
 * Calendar instance.
 * @param cal
 * @return <code>cal</code>
 */
public Calendar addToCalendar(Calendar cal) {
    cal.add(Calendar.MILLISECOND, this.milliseconds);
    cal.add(Calendar.SECOND, this.seconds);
    cal.add(Calendar.MINUTE, this.minutes);
    cal.add(Calendar.HOUR, this.hours);
    cal.add(Calendar.DAY_OF_MONTH, this.days);
    cal.add(Calendar.MONTH, this.months);
    cal.add(Calendar.YEAR, this.years);
    return cal;
}
 
Example 9
Source File: TimeDurationTests.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public void testDuration() throws Exception {
    Calendar now = Calendar.getInstance();
    TimeDuration zeroDuration = TimeDuration.ZeroTimeDuration;
    assertFalse("zero equals null", zeroDuration.equals(null));
    Calendar newTime = (Calendar) now.clone();
    zeroDuration.addToCalendar(newTime);
    assertEquals("zero same calendar", now, newTime);
    assertDurationFields("zero(same zero calendar)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", new TimeDuration(zero, zero), false, true);
    assertDurationFields("zero(same now calendar)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", new TimeDuration(now, now), false, true);
    assertDurationFields("zero(empty parse)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", TimeDuration.parseDuration(""), false, true);
    assertDurationFields("zero(zero parse)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", TimeDuration.parseDuration("0:0:0:0:0:0:0"), false, true);
    assertDurationFields("zero(from null number)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", TimeDuration.fromNumber(null), false, true);
    assertDurationFields("zero(from null number)", 0, 0, 0, 0, 0, 0, 0, "0:0:0:0:0:0:0", TimeDuration.fromNumber(null), false, true);
    assertDuration("millisecond", 0, 0, 0, 0, 0, 0, 1);
    assertDuration("second", 0, 0 ,0 ,0, 0, 1, 0);
    assertDuration("minute", 0, 0, 0, 0, 1, 0, 0);
    assertDuration("hour", 0, 0, 0, 1, 0, 0, 0);
    assertDuration("day",  0, 0, 1, 0, 0, 0, 0);
    assertDuration("month", 0, 1, 0, 0, 0, 0, 0);
    assertDuration("year", 1, 0, 0, 0, 0, 0, 0);
    Calendar start = new com.ibm.icu.util.GregorianCalendar(1967, 1, 1, 0, 0, 0);
    start.set(Calendar.MILLISECOND, 0);
    Calendar end = (Calendar) start.clone();
    end.add(Calendar.MILLISECOND, 1);
    end.add(Calendar.SECOND, 1);
    end.add(Calendar.MINUTE, 1);
    end.add(Calendar.HOUR_OF_DAY, 1);
    end.add(Calendar.DAY_OF_MONTH, 1);
    end.add(Calendar.MONTH, 1);
    end.add(Calendar.YEAR, 1);
    assertDurationFields("pre-epoch elapsed time", 1, 1, 1, 1, 1, 1, 1, "1:1:1:1:1:1:1", new TimeDuration(start, end), false, false);
}
 
Example 10
Source File: TemporalExpressions.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
protected Calendar prepareCal(Calendar cal) {
    // Performs a "sane" skip forward in time - avoids time consuming loops
    // like incrementing every second from Jan 1 2000 until today
    Calendar skip = (Calendar) cal.clone();
    skip.setTime(this.start);
    long deltaMillis = cal.getTimeInMillis() - this.start.getTime();
    if (deltaMillis < 1000) {
        return skip;
    }
    long divisor = deltaMillis;
    if (this.freqType == Calendar.DAY_OF_MONTH) {
        divisor = 86400000;
    } else if (this.freqType == Calendar.HOUR) {
        divisor = 3600000;
    } else if (this.freqType == Calendar.MINUTE) {
        divisor = 60000;
    } else if (this.freqType == Calendar.SECOND) {
        divisor = 1000;
    } else {
        return skip;
    }
    long units = deltaMillis / divisor;
    units -= units % this.freqCount;
    skip.add(this.freqType, (int)units);
    while (skip.after(cal)) {
        skip.add(this.freqType, -this.freqCount);
    }
    return skip;
}
 
Example 11
Source File: InvitationCleanupJob.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  public void executeWithDB(final JobExecutionContext context) {
      try {
          log.info("Starting invitation clean up job");
          EPPolicyManager policyManager = (EPPolicyManager) CoreSpringFactory.getBean(EPPolicyManager.class);
          final Calendar cal = Calendar.getInstance();
          cal.add(Calendar.HOUR, -6);
          policyManager.cleanUpInvitations(cal.getTime());
      } catch (final Exception e) {
          // ups, something went completely wrong! We log this but continue next time
          log.error("Error while cleaning up invitation", e);
      }
      // db closed by JobWithDB class
  }
 
Example 12
Source File: UtilDateTime.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static Timestamp getWeekStart(Timestamp stamp, int daysLater, int weeksLater, TimeZone timeZone, Locale locale) {
    Calendar tempCal = toCalendar(stamp, timeZone, locale);
    tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
    tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek());
    tempCal.add(Calendar.WEEK_OF_MONTH, weeksLater);
    Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
    retStamp.setNanos(0);
    return retStamp;
}
 
Example 13
Source File: UtilDateTime.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static Timestamp getDayEnd(Timestamp stamp, Long daysLater, TimeZone timeZone, Locale locale) {
    Calendar tempCal = toCalendar(stamp, timeZone, locale);
    tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater.intValue());
    Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
    retStamp.setNanos(0);
    //MSSQL datetime field has accuracy of 3 milliseconds and setting the nano seconds cause the date to be rounded to next day
    return retStamp;
}
 
Example 14
Source File: BirtDateTime.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add num hours
 *
 * @param date
 * @param num
 * @return
 */
private static Date addHour( Date date, int num )
{
	Calendar startCal = getCalendar( date );

	startCal.add( Calendar.HOUR_OF_DAY, num );

	return startCal.getTime( );
}
 
Example 15
Source File: TemporalExpressions.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSubstitutionCandidate(Calendar cal, TemporalExpression expressionToTest) {
    Calendar checkCal = (Calendar) cal.clone();
    checkCal.add(Calendar.HOUR_OF_DAY, -1);
    while (!includesDate(checkCal)) {
        if (expressionToTest.includesDate(checkCal)) {
            return true;
        }
        checkCal.add(Calendar.HOUR_OF_DAY, -1);
    }
    return false;
}
 
Example 16
Source File: SimpleDateFormat.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
private void initializeDefaultCenturyStart(long baseTime) {
    defaultCenturyBase = baseTime;
    // clone to avoid messing up date stored in calendar object
    // when this method is called while parsing
    Calendar tmpCal = (Calendar)calendar.clone();
    tmpCal.setTimeInMillis(baseTime);
    tmpCal.add(Calendar.YEAR, -80);
    defaultCenturyStart = tmpCal.getTime();
    defaultCenturyStartYear = tmpCal.get(Calendar.YEAR);
}
 
Example 17
Source File: MonthToDateFunction.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public List<TimeMember> getResult( TimeMember member )
{
	List timeMembers = new ArrayList<TimeMember>( );
	String[] levelTypes = member.getLevelType( );
	int[] values = member.getMemberValue( );

	Calendar cal = new GregorianCalendar( TimeMemberUtil.getTimeZone( ),
			TimeMemberUtil.getDefaultLocale( ) );
	cal.clear( );
	String baseType = translateToCal( cal, levelTypes, values );
	
	if ( isCurrent )
	{
		int month = cal.get( Calendar.MONTH );
		while ( true )
		{
			if ( cal.get( Calendar.MONTH ) != month )
			{
				cal.add( Calendar.DAY_OF_YEAR, -1 );
				break;
			}
			cal.add( Calendar.DAY_OF_YEAR, 1 );
		}

	}
	int[] tmp;
	if ( baseType.equals( MONTH ) )
	{
		timeMembers.add( member );
	}
	else if ( baseType.equals( WEEK ) )
	{
		retrieveWeek( timeMembers, cal, levelTypes, "monthToDate" );
	}
	else if ( baseType.equals( DAY ) )
	{
		int dayOfMonth = cal.get( Calendar.DAY_OF_MONTH );
		for ( int i = 1; i <= dayOfMonth; i++ )
		{
			cal.set( Calendar.DAY_OF_MONTH, i );
			tmp = getValueFromCal( cal, levelTypes );
			TimeMember timeMember = new TimeMember( tmp, levelTypes );
			timeMembers.add( timeMember );
		}
	}

	return timeMembers;
}
 
Example 18
Source File: UtilDateTime.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static Timestamp adjustTimestamp(Timestamp stamp, Integer adjType, Integer adjQuantity) {
    Calendar tempCal = toCalendar(stamp);
    tempCal.add(adjType, adjQuantity);
    return new Timestamp(tempCal.getTimeInMillis());
}
 
Example 19
Source File: InfoDisplayController.java    From olat with Apache License 2.0 4 votes vote down vote up
public InfoDisplayController(final UserRequest ureq, final WindowControl wControl, final ModuleConfiguration config, final InfoSecurityCallback secCallback,
        final OLATResourceable ores, final String resSubPath, final String businessPath) {
    super(ureq, wControl);
    this.secCallback = secCallback;
    this.ores = ores;
    this.resSubPath = resSubPath;
    this.businessPath = businessPath;

    infoMessageManager = CoreSpringFactory.getBean(InfoMessageFrontendManager.class);
    maxResults = maxResultsConfig = getConfigValue(config, InfoCourseNodeConfiguration.CONFIG_LENGTH, 10);
    duration = getConfigValue(config, InfoCourseNodeConfiguration.CONFIG_DURATION, 90);

    if (duration > 0) {
        final Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, -duration);
        after = afterConfig = cal.getTime();
    }

    messagePanel = new Panel("messagePanel");
    messagePanel.addListener(this);
    messagesVC = createVelocityContainer("display");
    if (secCallback.canAdd()) {
        newInfoLink = LinkFactory.createButton("new_message", "new_message", messagesVC, this);
    }
    oldMsgsLink = LinkFactory.createButton("display.old_messages", "display.old_messages", messagesVC, this);
    newMsgsLink = LinkFactory.createButton("display.new_messages", "display.new_messages", messagesVC, this);
    messagePanel.setContent(messagesVC);
    putInitialPanel(messagePanel);

    // OLAT-6302 when a specific message is shown display the page that
    // contains the message. Jump in e.g. from portlet
    ContextEntry ce = wControl.getBusinessControl().popLauncherContextEntry();
    if (ce != null) { // a context path is left for me
        OLATResourceable businessPathResource = ce.getOLATResourceable();
        String typeName = businessPathResource.getResourceableTypeName();
        if ("InfoMessage".equals(typeName)) {
            Long messageId = businessPathResource.getResourceableId();
            if (messageId != null && messageId.longValue() > 0) {
                // currently no pageing is implemented, just page with all entries
                maxResults = -1;
                after = null;
            }
        }
    }

    // now load with configuration
    loadMessages();
}
 
Example 20
Source File: TrailingFunction.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
private void setToMonthEnd( Calendar cal )
{
	setToMonthStart( cal );
	cal.add( Calendar.MONTH, 1);
	cal.add( Calendar.DATE, -1 );
}