Java Code Examples for org.joda.time.DateTime#plusDays()

The following examples show how to use org.joda.time.DateTime#plusDays() . These examples are extracted from open source projects. 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
/**
 * Gets the interval date time.
 *
 * @param curr the curr
 * @param type the type
 * @param interval the interval
 * @return the interval date time
 */
protected static DateTime plusDateTime(DateTime curr, DateType type, int interval) {
    DateTime result = curr;
    if (DateType.YEAR.equals(type)) {
        result = curr.plusYears(interval);
    } else if (DateType.MONTH.equals(type)) {
        result = curr.plusMonths(interval);
    } else if (DateType.WEEK.equals(type)) {
        result = curr.plusWeeks(interval);
    } else if (DateType.DAY.equals(type)) {
        result = curr.plusDays(interval);
    } else if (DateType.HOUR.equals(type)) {
        result = curr.plusHours(interval);
    } else if (DateType.MINUTE.equals(type)) {
        result = curr.plusMinutes(interval);
    } else if (DateType.SECOND.equals(type)) {
        result = curr.plusSeconds(interval);
    }
    return result;
}
 
Example 2
private LineChartData getLineChartData(List<Line> lines) {
    DateTime daysAgo = new DateTime().withTimeAtStartOfDay().minusDays(StatisticViewModel.DAYS_OF_ADDED_MODEL - 1);
    List<String> days = new ArrayList<>();
    SimpleDateFormat sdf = new SimpleDateFormat("dd", Locale.getDefault());
    for (int i=0; i<StatisticViewModel.DAYS_OF_ADDED_MODEL; i++){
        days.add(sdf.format(daysAgo.toDate()));
        daysAgo = daysAgo.plusDays(1);
    }

    LineChartData data = new LineChartData();
    data.setLines(lines);
    data.setAxisXBottom(null);
    data.setAxisYLeft(null);
    data.setBaseValue(-0.1f);
    data.setValueLabelBackgroundColor(Color.TRANSPARENT);
    Axis axis = Axis.generateAxisFromCollection(Arrays.asList(0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f), days);
    data.setAxisXBottom(axis);
    return data;
}
 
Example 3
Source Project: joda-time-android   File: TestDateUtils.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRelativeTimeSpanStringWithPreposition() {
    Context ctx = InstrumentationRegistry.getInstrumentation().getContext();

    LocalDate today = LocalDate.now();
    LocalDate tomorrow = today.plusDays(1);
    LocalDate nextYear = today.plusYears(1);

    assertEquals("12:35", DateUtils.getRelativeTimeSpanString(ctx, today, false));
    assertEquals("at 12:35", DateUtils.getRelativeTimeSpanString(ctx, today, true));
    assertEquals("Oct 23, 1995", DateUtils.getRelativeTimeSpanString(ctx, tomorrow, false));
    assertEquals("on Oct 23, 1995", DateUtils.getRelativeTimeSpanString(ctx, tomorrow, true));
    assertEquals("10/22/1996", DateUtils.getRelativeTimeSpanString(ctx, nextYear, false));
    assertEquals("on 10/22/1996", DateUtils.getRelativeTimeSpanString(ctx, nextYear, true));

    DateTime todayDt = DateTime.now();
    DateTime tomorrowDt = todayDt.plusDays(1);
    DateTime nextYearDt = todayDt.plusYears(1);

    assertEquals("12:35", DateUtils.getRelativeTimeSpanString(ctx, todayDt, false));
    assertEquals("at 12:35", DateUtils.getRelativeTimeSpanString(ctx, todayDt, true));
    assertEquals("Oct 23, 1995", DateUtils.getRelativeTimeSpanString(ctx, tomorrowDt, false));
    assertEquals("on Oct 23, 1995", DateUtils.getRelativeTimeSpanString(ctx, tomorrowDt, true));
    assertEquals("10/22/1996", DateUtils.getRelativeTimeSpanString(ctx, nextYearDt, false));
    assertEquals("on 10/22/1996", DateUtils.getRelativeTimeSpanString(ctx, nextYearDt, true));
}
 
Example 4
/**
 * Add a criteria to get the Risks for the given day
 *
 * @param query
 * @param date yyyy-MM-dd or latest
 */
private void dayCriteria(Query query, String date){
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    if (!date.isEmpty()) {
        if (date.equals("latest")){
            query.limit(1);
        } else {
            try {
                DateTime startDate = formatter.parseDateTime(date).withZone(DateTimeZone.UTC);
                DateTime endDate = startDate.plusDays(1);
                query.addCriteria(where("dateTime").gte(startDate).lt(endDate)); // Get the risks for the day given
            } catch (Exception e) {
                throw new BadRequestException("Not able to parse the date, it has to be in the following format: `yyyy-MM-dd` ");
            }
        }
    }
}
 
Example 5
Source Project: nomulus   File: CreateTldCommandTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_eapFeeSchedule() throws Exception {
  DateTime now = DateTime.now(UTC);
  DateTime tomorrow = now.plusDays(1);
  runCommandForced(
      String.format(
          "--eap_fee_schedule=\"%s=USD 0.00,%s=USD 50.00,%s=USD 10.00\"",
          START_OF_TIME, now, tomorrow),
      "--roid_suffix=Q9JYB4C",
      "--dns_writers=VoidDnsWriter",
      "xn--q9jyb4c");

  Registry registry = Registry.get("xn--q9jyb4c");
  assertThat(registry.getEapFeeFor(now.minusHours(1)).getCost())
      .isEqualTo(BigDecimal.ZERO.setScale(2, ROUND_UNNECESSARY));
  assertThat(registry.getEapFeeFor(now.plusHours(1)).getCost())
      .isEqualTo(new BigDecimal("50.00"));
  assertThat(registry.getEapFeeFor(now.plusDays(1).plusHours(1)).getCost())
      .isEqualTo(new BigDecimal("10.00"));
}
 
Example 6
public boolean getCanValidateContacts() {
    final DateTime now = new DateTime();
    final DateTime requestDate = getLastValidationRequestDate();
    if (requestDate == null || getNumberOfValidationRequests() == null) {
        return true;
    }
    final DateTime plus30 = requestDate.plusDays(30);
    if (now.isAfter(plus30) || now.isEqual(plus30)) {
        setNumberOfValidationRequests(0);
    }
    return getNumberOfValidationRequests() <= MAX_VALIDATION_REQUESTS;
}
 
Example 7
@PreAuthorize ("isAuthenticated ()")
@Transactional (readOnly=true, propagation=Propagation.REQUIRED)
@Cacheable (value = "product_eviction_date", key = "#pid")
public Date getEvictionDate (Long pid)
{
   Eviction eviction = evictionDao.getEviction (); 
   if (eviction.getStrategy () == EvictionStrategy.NONE)
   {
      return null;
   }
   Product p = productDao.read (pid);
   DateTime dt = new DateTime (p.getIngestionDate ());
   DateTime res = dt.plusDays (eviction.getKeepPeriod ());
   return res.toDate ();
}
 
Example 8
Source Project: liteflow   File: DateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取时间区间内的日期数
 *
 * @param start
 * @param end
 * @return
 */
public static List<Date> getBetweenDates(String start, String end) {
    List<Date> dates = Lists.newLinkedList();
    DateTime startDate = new DateTime(formatToDate(start));
    DateTime endDate = new DateTime(formatToDate(end));
    while (startDate.compareTo(endDate) <= 0) {
        dates.add(startDate.toDate());
        startDate = startDate.plusDays(1);
    }
    return dates;
}
 
Example 9
Source Project: bateman   File: TimeSeries.java    License: MIT License 5 votes vote down vote up
void removeDays(int i) {
    DateTime first = beginningOfSeries();
    DateTime midnight = first.toDateMidnight().toDateTime();
    DateTime cutoff = midnight.plusDays(i);

    prices = new TreeMap<DateTime, BigDecimal>(prices.tailMap(cutoff));
}
 
Example 10
private Subject createSubject(final String subjectId, final Integer samlAssertionDays) {
	DateTime currentDate = new DateTime();
	if (samlAssertionDays != null)
		currentDate = currentDate.plusDays(samlAssertionDays);
	
	// create name element
	NameIDBuilder nameIdBuilder = new NameIDBuilder(); 
	NameID nameId = nameIdBuilder.buildObject();
	nameId.setValue(subjectId);
	nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");

	SubjectConfirmationDataBuilder dataBuilder = new SubjectConfirmationDataBuilder();
	SubjectConfirmationData subjectConfirmationData = dataBuilder.buildObject();
	subjectConfirmationData.setNotOnOrAfter(currentDate);
	
	SubjectConfirmationBuilder subjectConfirmationBuilder = new SubjectConfirmationBuilder();
	SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
	subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");
	subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);
	
	// create subject element
	SubjectBuilder subjectBuilder = new SubjectBuilder();
	Subject subject = subjectBuilder.buildObject();
	subject.setNameID(nameId);
	subject.getSubjectConfirmations().add(subjectConfirmation);
	
	return subject;
}
 
Example 11
private List<String> getDays(TimePeriod timePeriod, String format) {
    List<String> result = new ArrayList<String>();
    DateTime startDateTime = new DateTime(timePeriod.getStartDate());
    DateTime endDateTime = new DateTime(timePeriod.getEndDate());
    // TODO: locale hardcoded (used for weekdays)
    SimpleDateFormat formatter = new SimpleDateFormat(format, new Locale("sv", "SE", ""));
    while (startDateTime.isBefore(endDateTime)) {
        String dateStr = formatter.format(startDateTime.toDate());
        result.add(dateStr);
        startDateTime = startDateTime.plusDays(1);
    }
    return result;
}
 
Example 12
private static Timestamp countNextRepeatTime(Player player, QuestTemplate template) {
	int questCooltime = template.getQuestCoolTime();
	DateTime now = DateTime.now();
	DateTime repeatDate = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 9, 0, 0);
	if (template.isDaily()) {
		if (now.isAfter(repeatDate)) {
			repeatDate = repeatDate.plusHours(24);
		}
		PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1400855, "9"));
	}
	else if (template.getQuestCoolTime() > 0) {
		repeatDate = repeatDate.plusSeconds(template.getQuestCoolTime());
		// This quest can be re-attempted in %DURATIONDAY0s.
		PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402676, +questCooltime));
	}
	else {
		int daysToAdd = 7;
		int startDay = 7;
		for (QuestRepeatCycle weekDay : template.getRepeatCycle()) {
			int diff = weekDay.getDay() - repeatDate.getDayOfWeek();
			if (diff > 0 && diff < daysToAdd) {
				daysToAdd = diff;
			}
			if (startDay > weekDay.getDay()) {
				startDay = weekDay.getDay();
			}
		}
		if (startDay == daysToAdd) {
			daysToAdd = 7;
		}
		else if (daysToAdd == 7 && startDay < 7) {
			daysToAdd = 7 - repeatDate.getDayOfWeek() + startDay;
		}
		repeatDate = repeatDate.plusDays(daysToAdd);
		PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1400857, new DescriptionId(1800667), "9"));
	}
	return new Timestamp(repeatDate.getMillis());
}
 
Example 13
/**
 * Returns a date a number of workdays away. Saturday and Sundays are not considered working days.
 */
@Function("WORKDAY")
@FunctionParameters({
	@FunctionParameter("dateObject"),
	@FunctionParameter("workdays")})
public Date WORKDAY(Object dateObject, Integer workdays){
	Date convertedDate = convertDateObject(dateObject);
	if(convertedDate==null){
		logCannotConvertToDate();
		return null;
	}
	else{
		boolean lookBack = workdays<0;
		DateTime cursorDT=new DateTime(convertedDate);
		int remainingDays=Math.abs(workdays);
		while(remainingDays>0){
			int dayOfWeek = cursorDT.getDayOfWeek();
			if(!(dayOfWeek==DateTimeConstants.SATURDAY || 
					dayOfWeek==DateTimeConstants.SUNDAY)){
				// Decrement remaining days only when it is not Saturday or Sunday
				remainingDays--;
			}
			if(!lookBack) {
				cursorDT= dayOfWeek==DateTimeConstants.FRIDAY?cursorDT.plusDays(3):cursorDT.plusDays(1);
			}
			else {
				cursorDT= dayOfWeek==DateTimeConstants.MONDAY?cursorDT.minusDays(3):cursorDT.minusDays(1);
			}
		}
		return cursorDT.toDate();
	}
}
 
Example 14
Source Project: liteflow   File: TomorrowCalculator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public DateTime calculate(DateTime dateTime) {
    return dateTime.plusDays(1);
}
 
Example 15
Source Project: liteflow   File: YesterdayCalculator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public DateTime calculate(DateTime dateTime) {
    return dateTime.plusDays(-1);
}
 
Example 16
Source Project: nomulus   File: EppLifecycleDomainTest.java    License: Apache License 2.0 4 votes vote down vote up
/** Test that missing type= argument on launch create works in start-date sunrise. */
@Test
public void testDomainCreation_startDateSunrise_noType() throws Exception {
  // The signed mark is valid between 2013 and 2017
  DateTime sunriseDate = DateTime.parse("2014-09-08T09:09:09Z");
  DateTime gaDate = sunriseDate.plusDays(30);
  createTld(
      "example",
      ImmutableSortedMap.of(
          START_OF_TIME, PREDELEGATION,
          sunriseDate, START_DATE_SUNRISE,
          gaDate, GENERAL_AVAILABILITY));

  assertThatLogin("NewRegistrar", "foo-BAR2")
      .atTime(sunriseDate.minusDays(3))
      .hasResponse("generic_success_response.xml");

  createContactsAndHosts();

  // During start-date sunrise, create with mark will succeed but without will fail.
  // We also test we can delete without a mark.
  assertThatCommand("domain_info.xml", ImmutableMap.of("DOMAIN", "test-validate.example"))
      .atTime(sunriseDate.plusDays(1))
      .hasResponse(
          "response_error.xml",
          ImmutableMap.of(
              "CODE", "2303",
              "MSG", "The domain with given ID (test-validate.example) doesn't exist."));

  assertThatCommand("domain_create_start_date_sunrise_encoded_mark_no_type.xml")
      .atTime(sunriseDate.plusDays(1).plusMinutes(1))
      .hasResponse(
          "domain_create_response.xml",
          ImmutableMap.of(
              "DOMAIN", "test-validate.example",
              "CRDATE", "2014-09-09T09:10:09Z",
              "EXDATE", "2015-09-09T09:10:09Z"));

  assertThatCommand("domain_info.xml", ImmutableMap.of("DOMAIN", "test-validate.example"))
      .atTime(sunriseDate.plusDays(1).plusMinutes(2))
      .hasResponse(
          "domain_info_response_ok_wildcard.xml",
          ImmutableMap.of(
              "DOMAIN", "test-validate.example",
              "CRDATE", "2014-09-09T09:10:09Z",
              "EXDATE", "2015-09-09T09:10:09Z"));

  assertThatLogoutSucceeds();
}
 
Example 17
Source Project: liteflow   File: DateUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 获取明天的日期
 *
 * @return
 */
public static Date getTomorrowDate() {
    DateTime dateTime = new DateTime();
    dateTime = dateTime.plusDays(1);
    return dateTime.toDate();
}
 
Example 18
Source Project: liteflow   File: DateUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 获取明天longDate->20180801
 * @return
 */
public static long getTommorrowLongDate() {
    DateTime dateTime = new DateTime();
    dateTime = dateTime.plusDays(1);
    return Long.parseLong(dateTime.toString("yyyyMMdd"));
}
 
Example 19
Source Project: Cubert   File: AggregateRewriter.java    License: Apache License 2.0 4 votes vote down vote up
private void calculateIncrementalFactLoadDates() throws AggregateRewriteException
{
    if (!this.mvExists)
        return;

    DateTime dt = null;
    /*
     * difference between factStartDate and mvHorizonDate determines #of bit shifts.
     * the new horizon date is always determined by the factStartDate.
     */
    if (this.factStartDate > mvHorizonDate)
        throw new AggregateRewriteException(String.format("Fact start date(%d) in the future of mv horizon date(%d) ",
                                                          factStartDate,
                                                          mvHorizonDate));

    dt = DateTimeUtilities.getDateTime(Integer.toString(mvRefreshDate));
    incLoadDate = dt.plusDays(1);

    // Handle over-ride case.
    if (mvRefreshDateOverride != -1)
    {
        // if over-ridden time is before the physical MV refresh time
        if (mvRefreshDateOverride != 0 && mvRefreshDateOverride < mvRefreshDate)
            incLoadDate =
                    DateTimeUtilities.getDateTime(Integer.toString(mvRefreshDateOverride))
                                     .plusDays(1);

        /*
         * mvRefreshDateOverride of 0 is treated as a hint to turn off
         * incrementalization.
         */
        else if (mvRefreshDateOverride == 0)
            incLoadDate = null;
    }

    if (mvRefreshDate != 0 && incLoadDate != null)
    {
        if (!(DateTimeUtilities.getDateTime(factStartDate).isBefore(incLoadDate) && DateTimeUtilities.getDateTime(factEndDate)
                                                                                                     .isAfter(incLoadDate)))
            throw new AggregateRewriteException(String.format("MV date range mis-matches load range[%s, %s] mvRefreshDate=%s ",
                                                              factStartDate,
                                                              factEndDate,
                                                              mvRefreshDate));
    }

}
 
Example 20
Source Project: AsuraFramework   File: DateCalculator.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * 获得日期前几天或者后几天的日期
 *
 * @param date 指定的日期
 * @param days 前后的天数,为负数,则为前几天,正数则为后几天
 * @return
 */
public static Date getDate(@NotNull Date date, int days) {
    Objects.requireNonNull(date, "date must not null");
    DateTime dateTime = new DateTime(date);
    dateTime = dateTime.plusDays(days);
    return dateTime.toDate();
}