Java Code Examples for org.apache.commons.lang3.time.DateUtils#addDays()

The following examples show how to use org.apache.commons.lang3.time.DateUtils#addDays() . 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: OffsetTest.java    From JavaBase with MIT License 6 votes vote down vote up
private void signIn() {

    if (DateUtils.isSameDay(new Date(), lastSignInTime)) {
      log.debug("is same day");
      return;
    }

    Date yesterday = DateUtils.addDays(new Date(), -1);
    yesterday = DateUtils.setHours(yesterday, 0);
    yesterday = DateUtils.setMinutes(yesterday, 0);

    log.debug("compare: lastSignInTime={}, yesterday={}", lastSignInTime, yesterday);

    if (lastSignInTime.before(yesterday)) {
      System.out.println(1);
    } else {
      System.out.println("+1");
    }

  }
 
Example 2
Source File: DataMigratorIntegrationTest.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testUpdateTicketReservation() {
    List<TicketCategoryModification> categories = Collections.singletonList(
            new TicketCategoryModification(null, "default", AVAILABLE_SEATS,
                    new DateTimeModification(LocalDate.now(), LocalTime.now()),
                    new DateTimeModification(LocalDate.now(), LocalTime.now()),
                    DESCRIPTION, BigDecimal.TEN, false, "", false, null, null, null, null, null, 0, null, null, AlfioMetadata.empty()));
    Pair<Event, String> eventUsername = initEvent(categories); 
    Event event = eventUsername.getKey();
    try {
     TicketReservationModification trm = new TicketReservationModification();
     trm.setAmount(1);
     trm.setTicketCategoryId(eventManager.loadTicketCategories(event).get(0).getId());
     TicketReservationWithOptionalCodeModification r = new TicketReservationWithOptionalCodeModification(trm, Optional.empty());
     Date expiration = DateUtils.addDays(new Date(), 1);
     String reservationId = ticketReservationManager.createTicketReservation(event, Collections.singletonList(r), Collections.emptyList(), expiration, Optional.empty(), Locale.ENGLISH, false);
     dataMigrator.fillReservationsLanguage();
     TicketReservation ticketReservation = ticketReservationManager.findById(reservationId).get();
     assertEquals("en", ticketReservation.getUserLanguage());
    } finally {
    	eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}
 
Example 3
Source File: GetWorkCalendarEndTimeCmd.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * 根据日期拿到对应的规则
 * @param date
 * @return
 */
private CalendarRuleEntity getCalendarRuleByDate(Date date) {
	CalendarRuleEntity calendarRuleEntity = null;
	for (CalendarRuleEntity calendarRuleEntity2 : calendarTypeEntity.getCalendarRuleEntities()) {
		if(calendarRuleEntity2.getWeek()==DateCalUtils.dayForWeek(date)) {
			calendarRuleEntity = calendarRuleEntity2;
		}
		if(calendarRuleEntity2.getWorkdate()!=null && DateUtils.isSameDay(calendarRuleEntity2.getWorkdate(), date) && calendarRuleEntity2.getCalendarPartEntities().size()!=0) {
			calendarRuleEntity = calendarRuleEntity2;
		}
	}
	//如果这天没有规则则再加一天
	if(calendarRuleEntity==null) {
		date = DateUtils.addDays(date, 1);
		return getCalendarRuleByDate(date);
	}
	return calendarRuleEntity;
}
 
Example 4
Source File: Clean.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<Instant> listInstant(Business business) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Instant.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Instant> cq = cb.createQuery(Instant.class);
	Root<Instant> root = cq.from(Instant.class);
	Date limit = DateUtils.addDays(new Date(), -Config.communicate().clean().getKeep());
	Predicate p = cb.lessThan(root.get(Instant_.createTime), limit);
	return em.createQuery(cq.select(root).where(p)).setMaxResults(2000).getResultList();
}
 
Example 5
Source File: CleanUpScheduler.java    From vjtools with Apache License 2.0 5 votes vote down vote up
/**
 * Get scheduled delay for proactive gc task,cross-day setting is supported.<br/>
 * 01:30-02:40,some time between 01:30-02:40;<br/>
 * 180000,180 seconds later.
 */
public static long getDelayMillis(String time) {
	String pattern = "HH:mm";
	Date now = new Date();
	if (StringUtils.contains(time, "-")) {
		String start = time.split("-")[0];
		String end = time.split("-")[1];
		if (StringUtils.contains(start, ":") && StringUtils.contains(end, ":")) {
			Date d1 = getCurrentDateByPlan(start, pattern);
			Date d2 = getCurrentDateByPlan(end, pattern);
			while (d1.before(now)) {
				d1 = DateUtils.addDays(d1, 1);
			}

			while (d2.before(d1)) {
				d2 = DateUtils.addDays(d2, 1);
			}

			return RandomUtil.nextLong(d1.getTime() - now.getTime(), d2.getTime() - now.getTime());
		}
	} else if (StringUtils.isNumeric(time)) {
		return Long.parseLong(time);
	}

	// default
	return getDelayMillis("02:00-05:00");
}
 
Example 6
Source File: WxMaAnalysisServiceImplTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVisitPage() throws Exception {
  final WxMaAnalysisService service = wxMaService.getAnalysisService();
  Date twoDaysAgo = DateUtils.addDays(new Date(), -2);
  List<WxMaVisitPage> visitPages = service.getVisitPage(twoDaysAgo, twoDaysAgo);
  assertNotNull(visitPages);
  System.out.println(visitPages);
  System.out.println(visitPages.get(0).getPagePath());
  System.out.println(visitPages.get(0).getPageVisitPv());
}
 
Example 7
Source File: ValidationTools.java    From sample-timesheets with Apache License 2.0 5 votes vote down vote up
public HoursAndMinutes workHoursForPeriod(Date start, Date end, User user) {
    HoursAndMinutes dayHourPlan = HoursAndMinutes.fromBigDecimal(workTimeConfigBean.getUserWorkHourForDay(user));
    HoursAndMinutes totalWorkHours = new HoursAndMinutes();

    for (; start.getTime() <= end.getTime(); start = DateUtils.addDays(start, 1)) {
        if (workdaysTools.isWorkday(start)) {
            totalWorkHours.add(dayHourPlan);
        }
    }
    return totalWorkHours;
}
 
Example 8
Source File: CleanUpScheduler.java    From vjtools with Apache License 2.0 5 votes vote down vote up
/**
 * Get scheduled delay for proactive gc task,cross-day setting is supported.<br/>
 * 01:30-02:40,some time between 01:30-02:40;<br/>
 * 180000,180 seconds later.
 */
public static long getDelayMillis(String time) {
	String pattern = "HH:mm";
	Date now = new Date();
	if (StringUtils.contains(time, "-")) {
		String start = time.split("-")[0];
		String end = time.split("-")[1];
		if (StringUtils.contains(start, ":") && StringUtils.contains(end, ":")) {
			Date d1 = getCurrentDateByPlan(start, pattern);
			Date d2 = getCurrentDateByPlan(end, pattern);
			while (d1.before(now)) {
				d1 = DateUtils.addDays(d1, 1);
			}

			while (d2.before(d1)) {
				d2 = DateUtils.addDays(d2, 1);
			}

			return RandomUtil.nextLong(d1.getTime() - now.getTime(), d2.getTime() - now.getTime());
		}
	} else if (StringUtils.isNumeric(time)) {
		return Long.parseLong(time);
	}

	// default
	return getDelayMillis("02:00-05:00");
}
 
Example 9
Source File: SimpleWeeklyTimesheets.java    From sample-timesheets with Apache License 2.0 5 votes vote down vote up
protected void updateDayColumnsCaptions() {
    for (Date current = firstDayOfWeek; current.getTime() <= lastDayOfWeek.getTime(); current = DateUtils.addDays(current, 1)) {
        DayOfWeek day = DayOfWeek.fromCalendarDay(DateTimeUtils.getCalendarDayOfWeek(current));
        String columnId = day.getId() + COLUMN_SUFFIX;
        weeklyTsTable.getColumn(columnId).setCaption(ScreensHelper.getColumnCaption(day.getId(), current));
    }
}
 
Example 10
Source File: WxMaAnalysisServiceImplTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVisitDistribution() throws Exception {
  final WxMaAnalysisService service = wxMaService.getAnalysisService();
  Date twoDaysAgo = DateUtils.addDays(new Date(), -2);
  WxMaVisitDistribution distribution = service.getVisitDistribution(twoDaysAgo, twoDaysAgo);
  assertNotNull(distribution);
  String date = DateFormatUtils.format(twoDaysAgo, "yyyyMMdd");
  assertEquals(date, distribution.getRefDate());
  assertTrue(distribution.getList().containsKey("access_source_session_cnt"));
  assertTrue(distribution.getList().containsKey("access_staytime_info"));
  assertTrue(distribution.getList().containsKey("access_depth_info"));
  System.out.println(distribution);
}
 
Example 11
Source File: WxMaAnalysisServiceImplTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMonthlyVisitTrend() throws Exception {
  Date now = new Date();
  Date firstDayOfThisMonth = DateUtils.setDays(now, 1);
  Date lastDayOfLastMonth = DateUtils.addDays(firstDayOfThisMonth, -1);
  Date firstDayOfLastMonth = DateUtils.addMonths(firstDayOfThisMonth, -1);

  final WxMaAnalysisService service = wxMaService.getAnalysisService();
  List<WxMaVisitTrend> trends = service.getMonthlyVisitTrend(firstDayOfLastMonth, lastDayOfLastMonth);
  assertEquals(1, trends.size());
  System.out.println(trends);
}
 
Example 12
Source File: Contents.java    From jease with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Deletes all objects older than given days in all Trash objects in the
 * system.
 */
public static void emptyTrash(int daysToKeep) {
    Date pivotDate = DateUtils.addDays(new Date(), -daysToKeep);
    for (Trash trash : Database.query(Trash.class)) {
        if (ArrayUtils.isNotEmpty(trash.getChildren())) {
            for (Content content : trash.getChildren(Content.class)) {
                if (content.getLastModified().before(pivotDate)) {
                    if (Contents.isDeletable(content)) {
                        Contents.delete(content);
                    }
                }
            }
        }
    }
}
 
Example 13
Source File: WxMaAnalysisServiceImplTest.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDailySummaryTrend() throws Exception {
  final WxMaAnalysisService service = wxMaService.getAnalysisService();
  Date twoDaysAgo = DateUtils.addDays(new Date(), -2);
  List<WxMaSummaryTrend> trends = service.getDailySummaryTrend(twoDaysAgo, twoDaysAgo);
  assertEquals(1, trends.size());
  System.out.println(trends);
}
 
Example 14
Source File: AdminServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public PasswordState getPasswordState(ComAdmin admin) {
	if (admin.isOneTimePassword()) {
		// One-time password must be changed immediately upon log on.
		return PasswordState.ONE_TIME;
	}

	int expirationDays = configService.getIntegerValue(ConfigValue.UserPasswordExpireDays, admin.getCompanyID());
	if (expirationDays <= 0) {
		// Expiration is disabled for company.
		return PasswordState.VALID;
	}

	// A password is valid for N days after its last change.
	Date expirationDate = DateUtils.addDays(admin.getLastPasswordChange(), expirationDays);

	if (DateUtilities.isPast(expirationDate)) {
		int expirationLockDays = configService.getIntegerValue(ConfigValue.UserPasswordFinalExpirationDays, admin.getCompanyID());

		// A password is still can be used to log in during N days after its expiration.
		Date expirationLockDate = DateUtils.addDays(expirationDate, expirationLockDays);

		if (DateUtilities.isPast(expirationLockDate)) {
			return PasswordState.EXPIRED_LOCKED;
		} else {
			return PasswordState.EXPIRED;
		}
	} else {
		int expirationWarningDays = configService.getIntegerValue(ConfigValue.UserPasswordExpireNotificationDays, admin.getCompanyID());

		// User should get a warning message for N days before password is expired.
		Date expirationWarningDate = DateUtils.addDays(expirationDate, -expirationWarningDays);

		if (DateUtilities.isPast(expirationWarningDate)) {
			return PasswordState.EXPIRING;
		} else {
			return PasswordState.VALID;
		}
	}
}
 
Example 15
Source File: User.java    From init-spring with Apache License 2.0 4 votes vote down vote up
@PrePersist
@PreUpdate
public void preUpdate() {
    if (this.passwordHash != null && !this.passwordHash.equals(this.storedPassword))
        this.expirationDate = DateUtils.addDays(new Date(), 90);
}
 
Example 16
Source File: TimeFrame.java    From dsworkbench with Apache License 2.0 4 votes vote down vote up
public List<Range<Long>> arriveTimespansToRanges() {
  List<Range<Long>> ranges = new LinkedList<>();
  Date arriveDate = DateUtils.truncate(new Date(arriveNotBefore), Calendar.DAY_OF_MONTH);

  for (TimeSpan span : arriveTimeSpans) {
    if(!span.isValidAtEveryDay()) {
        Range<Long> range;
        //just copy range
        range = Range.between(span.getSpan().getMinimum(), span.getSpan().getMaximum());
        
        if (range.getMaximum() > System.currentTimeMillis()) {
          if(range.getMinimum() <= System.currentTimeMillis()) {
              //rebuild Range
              range = Range.between(System.currentTimeMillis(), range.getMaximum());
          }
          //add range only if it is in future
          ranges.add(range);
        }
    }
    else {
      //span is valid for every day
      Date thisDate = new Date(arriveDate.getTime());
      //go through all days from start to end
      while (thisDate.getTime() < arriveNotAfter) {
        long spanStart = thisDate.getTime() + span.getSpan().getMinimum();
        long spanEnd = thisDate.getTime() + span.getSpan().getMaximum();
        Range<Long> newRange = null;
        //check span location relative to start frame
        if (spanStart >= arriveNotBefore && spanEnd > arriveNotBefore
            && spanStart < arriveNotAfter && spanEnd <= arriveNotAfter) {
          //|----------| (startNotBefore - startNotAfter)
          //  |----| (SpanStart - SpanEnd)
          newRange = Range.between(spanStart, spanEnd);
        } else if (spanStart < arriveNotBefore && spanEnd > arriveNotBefore
            && spanStart < arriveNotAfter && spanEnd <= arriveNotAfter) {
          //  |----------| (startNotBefore - startNotAfter)
          //|----| (SpanStart - SpanEnd)
          //set span start to 'startNotBefore'
          newRange = Range.between(arriveNotBefore, spanEnd);
        } else if (spanStart <= arriveNotBefore && spanEnd > arriveNotBefore
            && spanStart > arriveNotAfter && spanEnd >= arriveNotAfter) {
          //  |----------| (startNotBefore - startNotAfter)
          //|--------------| (SpanStart - SpanEnd)
          //set span start to 'startNotBefore'
          newRange = Range.between(arriveNotBefore, arriveNotAfter);
        } else if (spanStart >= arriveNotBefore && spanEnd > arriveNotBefore
            && spanStart < arriveNotAfter && spanEnd >= arriveNotAfter) {
          //|----------| (startNotBefore - startNotAfter)
          //    |---------| (SpanStart - SpanEnd)
          //set span start to 'startNotBefore'
          newRange = Range.between(spanStart, arriveNotAfter);
        }

        if (newRange != null) {
          if (newRange.getMinimum() < System.currentTimeMillis()) {
            //check minimum as current minimum is in past
            if (newRange.getMaximum() > System.currentTimeMillis()) {
              newRange = Range.between(System.currentTimeMillis(), newRange.getMaximum());
              ranges.add(newRange);
            }//ignore as entire range is in past
          } else {
            //add range as it is in future
            ranges.add(newRange);
          }
        }
        //increment current date by one day
        thisDate = DateUtils.addDays(thisDate, 1);
      }
    }
  }
  Collections.sort(ranges, new Comparator<Range<Long>>() {
    @Override
    public int compare(Range<Long> o1, Range<Long> o2) {
      return o1.getMinimum().compareTo(o2.getMinimum());
    }
  });
  return ranges;
}
 
Example 17
Source File: DateTimeUtils.java    From sample-timesheets with Apache License 2.0 4 votes vote down vote up
public static Date getLastDayOfWeek(Date date) {
    return DateUtils.addDays(getFirstDayOfWeek(date), 6);
}
 
Example 18
Source File: DateUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 减一天
 */
public static Date subDays(@NotNull final Date date, int amount) {
	return DateUtils.addDays(date, -amount);
}
 
Example 19
Source File: TimeFrame.java    From dsworkbench with Apache License 2.0 4 votes vote down vote up
public List<Range<Long>> startTimespansToRanges() {
  List<Range<Long>> ranges = new LinkedList<>();
  Date startDate = DateUtils.truncate(new Date(startNotBefore), Calendar.DATE);

  for (TimeSpan span : sendTimeSpans) {
    if(!span.isValidAtEveryDay()) {
        Range<Long> range;
        //just copy range
        if(span.isValidAtExactTime()) {
          range = Range.between(span.getSpan().getMinimum(), span.getSpan().getMaximum() + fixedStartTimeRangeSize);
        } else {
          range = Range.between(span.getSpan().getMinimum(), span.getSpan().getMaximum());
        }
        
        if (range.getMaximum() > System.currentTimeMillis()) {
          if(range.getMinimum() <= System.currentTimeMillis()) {
              //rebuild Range
              range = Range.between(System.currentTimeMillis(), range.getMaximum());
          }
          //add range only if it is in future
          ranges.add(range);
        }
    }
    else {
      //span is valid for every day
      Date thisDate = new Date(startDate.getTime());
      //go through all days from start to end
      while (thisDate.getTime() < startNotAfter) {
        long spanStart = thisDate.getTime() + span.getSpan().getMinimum();
        long spanEnd = thisDate.getTime() + span.getSpan().getMaximum();
        Range<Long> newRange = null;
        //check span location relative to start frame
        if (spanStart >= startNotBefore && spanEnd > startNotBefore
            && spanStart < startNotAfter && spanEnd <= startNotAfter) {
          //|----------| (startNotBefore - startNotAfter)
          //  |----| (SpanStart - SpanEnd)
          newRange = Range.between(spanStart, spanEnd);
        } else if (spanStart < startNotBefore && spanEnd > startNotBefore
            && spanStart < startNotAfter && spanEnd <= startNotAfter) {
          //  |----------| (startNotBefore - startNotAfter)
          //|----| (SpanStart - SpanEnd)
          //set span start to 'startNotBefore'
          newRange = Range.between(startNotBefore, spanEnd);
        } else if (spanStart <= startNotBefore && spanEnd > startNotBefore
            && spanStart > startNotAfter && spanEnd >= startNotAfter) {
          //  |----------| (startNotBefore - startNotAfter)
          //|--------------| (SpanStart - SpanEnd)
          //set span start to 'startNotBefore'
          newRange = Range.between(startNotBefore, startNotAfter);
        } else if (spanStart >= startNotBefore && spanEnd > startNotBefore
            && spanStart < startNotAfter && spanEnd >= startNotAfter) {
          //|----------| (startNotBefore - startNotAfter)
          //    |---------| (SpanStart - SpanEnd)
          //set span start to 'startNotBefore'
          newRange = Range.between(spanStart, startNotAfter);
        }

        if (newRange != null) {
          if (newRange.getMinimum() < System.currentTimeMillis()) {
            //check minimum as current minimum is in past
            if (newRange.getMaximum() > System.currentTimeMillis()) {
              newRange = Range.between(System.currentTimeMillis(), newRange.getMaximum());
              ranges.add(newRange);
            }//ignore as entire range is in past
          } else {
            //add range as it is in future
            ranges.add(newRange);
          }
        }
        //increment current date by one day
        thisDate = DateUtils.addDays(thisDate, 1);
      }
    }
  }
  Collections.sort(ranges, new Comparator<Range<Long>>() {
    @Override
    public int compare(Range<Long> o1, Range<Long> o2) {
      return o1.getMinimum().compareTo(o2.getMinimum());
    }
  });
  return ranges;
}
 
Example 20
Source File: DateIncrementer.java    From tutorials with MIT License 4 votes vote down vote up
public static String addOneDayApacheCommons(String date) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date incrementedDate = DateUtils.addDays(sdf.parse(date), 1);
    return sdf.format(incrementedDate);
}