Java Code Examples for java.util.Calendar#add()

The following examples show how to use java.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: BlockServiceImpl.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
@Override
public Curve get20CountList() {
    List<Integer> integers = new LinkedList<>();
    Curve curve = new Curve();
    curve.setName("Block Count");
    for (int i = 19; i >= 0; i--) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 0 - i);
        int date = Integer.valueOf(DateUtil.date2Str(calendar.getTime(), "yyyyMMdd"));
        int blockCount = 0;
        try {
            blockCount = blockMapper.countByDate(date);
        } catch (Exception ignored) {

        }
        integers.add(blockCount);
    }
    int ud = integers.get(19) - integers.get(18);
    curve.setUpDown(ud >= 0 ? "+" + ud : String.valueOf(ud));
    curve.setIntegers(integers);
    return curve;
}
 
Example 2
Source File: 1_DurationFormatUtils.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
static int reduceAndCorrect(Calendar start, Calendar end, int field, int difference) {
        end.add( field, -1 * difference );
        int endValue = end.get(field);
        int startValue = start.get(field);
// start of generated patch
if(endValue<field){
int newdiff=startValue-endValue;
end.add(field,newdiff);
return newdiff;
}else {
return 0;
}
// end of generated patch
/* start of original code
        if (endValue < startValue) {
            int newdiff = startValue - endValue;
            end.add( field, newdiff );
            return newdiff;
        } else {
            return 0;
        }
 end of original code*/
    }
 
Example 3
Source File: SegmentedTimeline.java    From ccu-historian with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the milliseconds for midnight of the first Monday after
 * 1-Jan-1900, ignoring daylight savings.
 *
 * @return The milliseconds.
 *
 * @since 1.0.7
 */
public static long firstMondayAfter1900() {
    int offset = TimeZone.getDefault().getRawOffset();
    TimeZone z = new SimpleTimeZone(offset, "UTC-" + offset);

    // calculate midnight of first monday after 1/1/1900 relative to
    // current locale
    Calendar cal = new GregorianCalendar(z);
    cal.set(1900, 0, 1, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        cal.add(Calendar.DATE, 1);
    }
    //return cal.getTimeInMillis();
    // preceding code won't work with JDK 1.3
    return cal.getTime().getTime();
}
 
Example 4
Source File: DateUtil.java    From alcor with Apache License 2.0 6 votes vote down vote up
public static String localToUTC(String localTime, String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    Date localDate= null;
    try {
        localDate = sdf.parse(localTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long localTimeInMillis = localDate.getTime();

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(localTimeInMillis);
    int zoneOffset = calendar.get(java.util.Calendar.ZONE_OFFSET);
    int dstOffset = calendar.get(java.util.Calendar.DST_OFFSET);
    calendar.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
    Date utcDate = new Date(calendar.getTimeInMillis());
    String utc = sdf.format(utcDate);

    return utc;
}
 
Example 5
Source File: RedisLeaderManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void electLeader()
{
    log.debug( "Election attempt by nodeId:" + this.nodeId );
    redisTemplate.getConnectionFactory().getConnection().set( key.getBytes(), nodeId.getBytes(),
        Expiration.from( timeToLiveSeconds, TimeUnit.SECONDS ), SetOption.SET_IF_ABSENT );
    if ( isLeader() )
    {
        renewLeader();
        Calendar calendar = Calendar.getInstance();
        calendar.add( Calendar.SECOND, (int) (this.timeToLiveSeconds / 2) );
        log.debug( "Next leader renewal job nodeId:" + this.nodeId + " set at " + calendar.getTime().toString() );
        JobConfiguration leaderRenewalJobConfiguration = new JobConfiguration( CLUSTER_LEADER_RENEWAL,
            JobType.LEADER_RENEWAL, null, true );
        leaderRenewalJobConfiguration.setLeaderOnlyJob( true );
        schedulingManager.scheduleJobWithStartTime( leaderRenewalJobConfiguration, calendar.getTime() );
    }
}
 
Example 6
Source File: TagSensorReading.java    From com.ruuvi.station with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void removeOlderThan(int hours) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.HOUR, -hours);
    SQLite.delete()
            .from(TagSensorReading.class)
            .where(TagSensorReading_Table.createdAt.lessThan(cal.getTime()))
            .async()
            .execute();
}
 
Example 7
Source File: DateUtils.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
/**
 * 获取下一天的零点
 */
public static long getNewDay() {
	Calendar cal = Calendar.getInstance();
	cal.setTime(new Date());
	cal.set(Calendar.HOUR_OF_DAY, 0);
	cal.set(Calendar.MINUTE, 0);
	cal.set(Calendar.SECOND, 0);
	cal.set(Calendar.MILLISECOND, 0);
	cal.add(Calendar.DAY_OF_MONTH, 1);
	return  cal.getTimeInMillis();
}
 
Example 8
Source File: ZosmfSchemeTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private QueryResponse prepareQueryResponseForTime(int amountOfSeconds) {
    QueryResponse queryResponse = new QueryResponse();
    Calendar c = Calendar.getInstance();
    c.add(Calendar.SECOND, amountOfSeconds);
    queryResponse.setExpiration(c.getTime());
    return queryResponse;
}
 
Example 9
Source File: OrderServiceImpl.java    From java_server with MIT License 5 votes vote down vote up
public Long getPCOrdersCount(Short status, String search) {
	Calendar calendar=Calendar.getInstance();

	if(status!=1){
		calendar.add(Calendar.MONTH, -1);
		calendar.set(Calendar.DAY_OF_MONTH, 1);            //设定默认只显示近两个月的数据		
	}else{
		calendar.add(Calendar.DAY_OF_MONTH, -14);        //代发货订单默认显示两周内订单
	}
	
	return orderMapper.getPCOrdersCount(status,calendar.getTime(),search);
}
 
Example 10
Source File: ScriptAddedFunctions.java    From hop with Apache License 2.0 5 votes vote down vote up
public static Object getFiscalDate( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
                                    Object FunctionContext ) {

  if ( ArgList.length == 2 ) {
    try {
      if ( isNull( ArgList ) ) {
        return null;
      } else if ( isUndefined( ArgList ) ) {
        return undefinedValue;
      }
      java.util.Date dIn = (java.util.Date) ArgList[ 0 ];
      Calendar startDate = Calendar.getInstance();
      Calendar fisStartDate = Calendar.getInstance();
      Calendar fisOffsetDate = Calendar.getInstance();
      startDate.setTime( dIn );
      Format dfFormatter = new SimpleDateFormat( "dd.MM.yyyy" );
      String strOffsetDate = (String) ArgList[ 1 ] + String.valueOf( startDate.get( Calendar.YEAR ) );
      java.util.Date dOffset = (java.util.Date) dfFormatter.parseObject( strOffsetDate );
      fisOffsetDate.setTime( dOffset );

      String strFisStartDate = "01.01." + String.valueOf( startDate.get( Calendar.YEAR ) + 1 );
      fisStartDate.setTime( (java.util.Date) dfFormatter.parseObject( strFisStartDate ) );
      int iDaysToAdd = (int) ( ( startDate.getTimeInMillis() - fisOffsetDate.getTimeInMillis() ) / 86400000 );
      fisStartDate.add( Calendar.DATE, iDaysToAdd );
      return fisStartDate.getTime();
    } catch ( Exception e ) {
      throw new RuntimeException( e.toString() );
    }
  } else {
    throw new RuntimeException( "The function call getFiscalDate requires 2 arguments." );
  }

}
 
Example 11
Source File: DateUtil.java    From BaseProject with MIT License 5 votes vote down vote up
/**
 * 返回某月份的最后一天
 */
public static Date getLastDayByMonth(@NonNull Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.MONTH, 1);
    calendar.add(Calendar.DAY_OF_MONTH, -1);
    return calendar.getTime();
}
 
Example 12
Source File: StatsManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public SummaryVisitsChartData getSummaryVisitsChartData(String siteId, String viewType){
	SummaryVisitsChartData svc = new SummaryVisitsChartDataImpl(viewType);
	Calendar c = Calendar.getInstance();
	c.set(Calendar.HOUR_OF_DAY, 23);
	c.set(Calendar.MINUTE, 59);
	c.set(Calendar.SECOND, 59);
	Date finalDate = c.getTime();
	Date initialDate = null;
	
	List<SiteVisits> siteVisits = null;
	if(VIEW_WEEK.equals(viewType)){
		c.add(Calendar.DATE, -6);
		initialDate = c.getTime();
		siteVisits = getSiteVisits(siteId, initialDate, finalDate);
	}else if(VIEW_MONTH.equals(viewType)){
		c.add(Calendar.DATE, -29);
		initialDate = c.getTime();
		siteVisits = getSiteVisits(siteId, initialDate, finalDate);
	}else if(VIEW_YEAR.equals(viewType)){
		c.add(Calendar.MONTH, -11);
		initialDate = c.getTime();
		siteVisits = getSiteVisitsByMonth(siteId, initialDate, finalDate);
	}
	//log.info("siteVisits of [siteId:"+siteId+"] from ["+initialDate.toGMTString()+"] to ["+finalDate.toGMTString()+"]: "+siteVisits.toString());
	svc.setSiteVisits(siteVisits);
	return (siteVisits != null && siteVisits.size() > 0)? svc : null;
}
 
Example 13
Source File: TimeUtils.java    From Doradus with Apache License 2.0 4 votes vote down vote up
public static Calendar getPeriodEnd(Calendar calendar, String units) {

        Calendar c1 = (Calendar) calendar.clone();

        switch (functions.get(units)) {
            case 1:  //This minute
                c1.set(Calendar.SECOND, 0);
                c1.set(Calendar.MILLISECOND, 0);
                c1.add(Calendar.MINUTE, 1);

                break;
            case 2:  //This hour
                c1.set(Calendar.MINUTE, 0);
                c1.set(Calendar.SECOND, 0);
                c1.set(Calendar.MILLISECOND, 0);
                c1.add(Calendar.HOUR_OF_DAY, 1);
                break;
            case 3:  //today
                c1.clear(Calendar.AM_PM);
                c1.set(Calendar.HOUR_OF_DAY, 0);
                c1.set(Calendar.MINUTE, 0);
                c1.set(Calendar.SECOND, 0);
                c1.set(Calendar.MILLISECOND, 0);
                c1.add(Calendar.DAY_OF_YEAR, 1);
                break;
            case 4:  //this week
                c1.set(Calendar.DAY_OF_WEEK, c1.getFirstDayOfWeek());
                c1.clear(Calendar.AM_PM);
                c1.set(Calendar.HOUR_OF_DAY, 0);
                c1.set(Calendar.MINUTE, 0);
                c1.set(Calendar.SECOND, 0);
                c1.set(Calendar.MILLISECOND, 0);
                c1.add(Calendar.WEEK_OF_YEAR, 1);
                break;
            case 5:  //this month
                c1.set(Calendar.DAY_OF_MONTH, 1);
                c1.clear(Calendar.AM_PM);
                c1.set(Calendar.HOUR_OF_DAY, 0);
                c1.set(Calendar.MINUTE, 0);
                c1.set(Calendar.SECOND, 0);
                c1.set(Calendar.MILLISECOND, 0);
                c1.add(Calendar.MONTH, 1);
                break;
            case 6:  //this year
                c1.clear(Calendar.AM_PM);
                c1.set(Calendar.HOUR_OF_DAY, 0);
                c1.set(Calendar.MINUTE, 0);
                c1.set(Calendar.SECOND, 0);
                c1.set(Calendar.MILLISECOND, 0);
                c1.set(Calendar.DAY_OF_YEAR, 1);
                c1.add(Calendar.YEAR, 1);
                break;
            default:
                break;
        }
        return c1;
    }
 
Example 14
Source File: DateHelper.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date getJustDay(int type, int count) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(type, count);
    return calendar.getTime();
}
 
Example 15
Source File: TestDayOfWeekFilter.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Test
public void testSomeDays() {
   ScheduledEvent event;
   DayOfWeekFilter filter = new DayOfWeekFilter(AlwaysFireCondition.getInstance(), EnumSet.of(DayOfWeek.MONDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY));
   AttributeValueChangedEvent valueChangeEvent = AttributeValueChangedEvent.create(
         Address.platformDriverAddress(UUID.randomUUID()),
         "test:attribute", 
         "value", 
         null
   );
   
   Calendar expectedChangeTime = new TimeOfDay(0, 00, 00).on(day(Calendar.MONDAY));
   Calendar valueChangeTime = new TimeOfDay(8, 00, 00).on(day(Calendar.MONDAY));
   
   assertTrue(filter.isSatisfiable(context));
   assertEquals("When an event happens on MONDAY,THURSDAY,FRIDAY", filter.toString());
   
   // activate on Monday
   context.setLocalTime(expectedChangeTime);
   filter.activate(context);
   assertTrue(filter.isActive());
   event = context.getEvents().poll();
   assertNotNull(event);
   expectedChangeTime.add(Calendar.DAY_OF_WEEK, 1);
   assertDateEquals(expectedChangeTime.getTimeInMillis(), event.getScheduledTimestamp());
   
   // monday
   context.setLocalTime(valueChangeTime);
   assertTrue(filter.shouldFire(context, valueChangeEvent));
   
   // de-activate on Tuesday
   context.setLocalTime(expectedChangeTime);
   assertFalse(filter.shouldFire(context, event));
   assertFalse(filter.isActive());
   event = context.getEvents().poll();
   assertNotNull(event);
   expectedChangeTime.add(Calendar.DAY_OF_WEEK, 2);
   assertDateEquals(expectedChangeTime.getTimeInMillis(), event.getScheduledTimestamp());

   // tuesday
   valueChangeTime.add(Calendar.DAY_OF_WEEK, 1);
   context.setLocalTime(valueChangeTime);
   assertFalse(filter.shouldFire(context, valueChangeEvent));

   // wednesday
   valueChangeTime.add(Calendar.DAY_OF_WEEK, 1);
   context.setLocalTime(valueChangeTime);
   assertFalse(filter.shouldFire(context, valueChangeEvent));

   // re-activate start of thursday
   context.setLocalTime(expectedChangeTime);
   assertTrue(filter.shouldFire(context, event));
   assertTrue(filter.isActive());
   event = context.getEvents().poll();
   assertNotNull(event);
   expectedChangeTime.add(Calendar.DAY_OF_WEEK, 2);
   assertDateEquals(expectedChangeTime.getTimeInMillis(), event.getScheduledTimestamp());

   // thursday
   valueChangeTime.add(Calendar.DAY_OF_WEEK, 1);
   context.setLocalTime(valueChangeTime);
   assertTrue(filter.shouldFire(context, valueChangeEvent));
   
   // friday
   valueChangeTime.add(Calendar.DAY_OF_WEEK, 1);
   context.setLocalTime(valueChangeTime);
   assertTrue(filter.shouldFire(context, valueChangeEvent));
   
   // de-activate start of saturday
   context.setLocalTime(expectedChangeTime);
   assertFalse(filter.shouldFire(context, event));
   assertFalse(filter.isActive());
   event = context.getEvents().poll();
   assertNotNull(event);
   expectedChangeTime.add(Calendar.DAY_OF_WEEK, 2);
   assertDateEquals(expectedChangeTime.getTimeInMillis(), event.getScheduledTimestamp());

   // saturday
   valueChangeTime.add(Calendar.DAY_OF_WEEK, 1);
   context.setLocalTime(valueChangeTime);
   assertFalse(filter.shouldFire(context, valueChangeEvent));
   
   // sunday
   valueChangeTime.add(Calendar.DAY_OF_WEEK, 1);
   context.setLocalTime(valueChangeTime);
   assertFalse(filter.shouldFire(context, valueChangeEvent));
}
 
Example 16
Source File: NotificationServiceTemplateTranslationTest.java    From olat with Apache License 2.0 4 votes vote down vote up
private Calendar aMonthAgo() {
    Calendar lastSentNotificationMailAMonthAgo = GregorianCalendar.getInstance();
    lastSentNotificationMailAMonthAgo.add(GregorianCalendar.MONTH, -1);
    return lastSentNotificationMailAMonthAgo;
}
 
Example 17
Source File: ComWorkflowValidationService.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Check whether a mailtracking is enabled (if it's needed) and a maximum possible time period
 * between followed mailing and following one doesn't exceeds {@code trackingDays}.
 * @param icons workflow icons to process.
 * @param trackingDays mailtracking data expiration period (or 0 when a mailtracking is disabled).
 */
public List<MailingTrackingUsageError> checkMailingTrackingUsage(List<WorkflowIcon> icons, int trackingDays) {
    List<MailingTrackingUsageError> errors = new ArrayList<>();
    WorkflowGraph graph = new WorkflowGraph();

    if (!graph.build(icons)) {
        return errors;
    }

    final Set<Integer> mailingTypes = new HashSet<>(Arrays.asList(
            WorkflowIconType.MAILING.getId(),
            WorkflowIconType.ACTION_BASED_MAILING.getId(),
            WorkflowIconType.DATE_BASED_MAILING.getId(),
            WorkflowIconType.FOLLOWUP_MAILING.getId()
    ));

    for (WorkflowNode mailingNode : graph.getAllNodesByTypes(mailingTypes)) {
        WorkflowMailingAware mailingIcon = (WorkflowMailingAware) mailingNode.getNodeIcon();

        // Find all available incoming chains for this mailing icon
        List<List<WorkflowNode>> chains = workflowService.getChains(mailingIcon, icons, false);

        for (List<WorkflowNode> chain : chains) {
            boolean valid = true;
            boolean isLeadMailingNormal = isNormalMailing(mailingIcon);

            Date mailingDate = workflowService.getChainDate(chain);
            if (mailingDate == null) {
                continue;
            }

            // Skip mailing node itself (it's first in the chain)
            for (int i = 1; i < chain.size(); i++) {
                WorkflowIcon icon = chain.get(i).getNodeIcon();

                // A decision icon is treated as a termination one if it doesn't use a mailtracking data
                if (icon.getType() == WorkflowIconType.DECISION.getId()) {
                    WorkflowDecision decision = (WorkflowDecision) icon;

                    if (icon.isFilled()) {
                        if (decision.getDecisionType() == WorkflowDecisionType.TYPE_AUTO_OPTIMIZATION) {
                            // Auto optimization doesn't use a mailtracking data
                            break;
                        }
                        // Decision (reaction, yes-path only) doesn't use a mailtracking data
                        if (decision.getDecisionType() == WorkflowDecisionType.TYPE_DECISION &&
                                decision.getDecisionCriteria() == WorkflowDecisionCriteria.DECISION_REACTION &&
                                chain.get(i - 1) == graph.getDecisionYesBranch(chain.get(i))) {
                            // Whether the chain goes through decision's positive connection (yes-path)
                            break;
                        }
                    }
                } else if (WorkflowUtils.isMailingIcon(icon)) {
                    WorkflowMailingAware followedMailingIcon = (WorkflowMailingAware) icon;

                    if (trackingDays > 0) {
                        Date followedMailingDate = workflowService.getChainDate(chain, icon);
                        if (followedMailingDate == null) {
                            break;
                        }

                        Calendar expirationDate = Calendar.getInstance();
                        expirationDate.setTime(followedMailingDate);
                        expirationDate.add(Calendar.DAY_OF_YEAR, trackingDays);

                        if (mailingDate.after(expirationDate.getTime())) {
                            valid = false;
                            errors.add(new MailingTrackingUsageError(
                                    MailingTrackingUsageErrorType.EXPIRATION_PERIOD_EXCEEDED,
                                    followedMailingIcon.getMailingId()
                            ));
                        }
                    } else if(!isLeadMailingNormal || !isNormalMailing(icon)){
                        //Checks if mailtracking is disabled only normal mailings can be in queue

                        valid = false;
                        errors.add(new MailingTrackingUsageError(
                                MailingTrackingUsageErrorType.MAILING_TRACKING_DISABLED,
                                mailingIcon.getMailingId()
                        ));
                    }
                    break;
                }
            }

            // There's no sense to show multiple errors related to the same mailing icon
            if (!valid) {
                // Skip other chains starting with this mailing icon
                break;
            }
        }
    }

    return errors;
}
 
Example 18
Source File: DataProviderTimerBased.java    From development with Apache License 2.0 4 votes vote down vote up
private long addMonths(long millis, int months) {
    Calendar cal = getCalendar();
    cal.setTimeInMillis(millis);
    cal.add(Calendar.MONTH, months);
    return cal.getTimeInMillis();
}
 
Example 19
Source File: ProfileAndHomePageEditController.java    From olat with Apache License 2.0 4 votes vote down vote up
private Date createTimeoutDate(final UserRequest ureq, TemporaryKey tk) {
    final Calendar cal = Calendar.getInstance();
    cal.setTime(tk.getCreationDate());
    cal.add(Calendar.DAY_OF_WEEK, ChangeEMailController.TIME_OUT);
    return cal.getTime();
}
 
Example 20
Source File: DateTimeKit.java    From MeetingFilm with Apache License 2.0 3 votes vote down vote up
/**
 * 获取指定日期偏移指定时间后的时间
 *
 * @param date 基准日期
 * @param calendarField 偏移的粒度大小(小时、天、月等)使用Calendar中的常数
 * @param offsite 偏移量,正数为向后偏移,负数为向前偏移
 * @return 偏移后的日期
 */
public static DateTime offsiteDate(Date date, int calendarField, int offsite) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	cal.add(calendarField, offsite);
	return new DateTime(cal.getTime());
}