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

The following examples show how to use org.joda.time.DateTime#minusDays() . 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
private DateTime calculateReminderTime(DateTime date, int inputAmount, int inputChoice)
{
    DateTime dateTime = new DateTime();

    switch ( inputChoice )
    {
        case 0:
            dateTime = date.minusMinutes(inputAmount);
            break;
        case 1:
            dateTime = date.minusHours(inputAmount);
            break;
        case 2:
            dateTime = date.minusDays(inputAmount);
            break;
        case 3:
            dateTime = date.minusWeeks(inputAmount);
    }

    return dateTime;
}
 
Example 2
Source Project: secure-data-service   File: DateHelper.java    License: Apache License 2.0 6 votes vote down vote up
public boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod) {
    boolean expired = false;
    if (null != body.get(fieldName)) {
        DateTime expire = DateTime.parse((String) body.get(fieldName), FMT);
        DateTime now = DateTime.now();

        if (useGracePeriod) {
            int numDays = Integer.parseInt(gracePeriod);
            now = now.minusDays(numDays);
        }

        expired = now.isAfter(expire);
    }

    return expired;
}
 
Example 3
Source Project: frostmourne   File: EsRestClientContainer.java    License: MIT License 5 votes vote down vote up
public String[] buildIndices(DateTime from, DateTime to, String prefix, String datePattern) {
    DateTime now = DateTime.now();
    if (now.getMillis() < to.getMillis()) {
        to = now;
    }
    List<String> indiceList = new ArrayList<>();
    if (Strings.isNullOrEmpty(datePattern)) {
        indiceList.add(prefix);
        return indiceList.toArray(new String[0]);
    }

    if (datePattern.equals("*")) {
        indiceList.add(prefix + "*");
        return indiceList.toArray(new String[0]);
    }

    DateTime cursor = DateTime.parse(from.minusDays(1).toString("yyyy-MM-dd"));

    while (cursor.getMillis() < to.getMillis()) {
        String index = prefix + cursor.toString(datePattern);
        if (prefix.contains("*")) {
            if (!indiceList.contains(index)) {
                indiceList.add(index);
            }
        } else if (checkIndexExists(index)) {
            if (!indiceList.contains(index)) {
                indiceList.add(index);
            }
        }
        cursor = cursor.minusDays(-1);
    }
    return indiceList.toArray(new String[0]);
}
 
Example 4
private DateTime startDateTime(int noOfWeeks) {
    // find first monday 
    DateTime result = new DateTime();
    while (true) {
        if (result.getDayOfWeek() == DateTimeConstants.MONDAY) {
            break;
        }
        result = result.minusDays(1);
    }
    return result.minusDays(7*noOfWeeks);
}
 
Example 5
Source Project: frostmourne   File: AbstractSameTimeMetric.java    License: MIT License 5 votes vote down vote up
/**
 * 根据结束时间和比较间隔类型获取开始时间
 *
 * @param end        结束时间
 * @param periodUnit 间隔类型
 * @return start time
 */
protected DateTime findStart(DateTime end, String periodUnit) {
    DateTime start;
    if (periodUnit.equalsIgnoreCase("HOUR")) {
        start = end.minusMinutes(60);
    } else if (periodUnit.equalsIgnoreCase("DAY")) {
        start = end.minusDays(1);
    } else {
        throw new IllegalArgumentException("unknown period unit: " + periodUnit);
    }
    return start;
}
 
Example 6
@Test
public void fromTweetsMapAgeDays() {
    DateTime now = DateTime.now();
    DateTime fourDaysAgo = now.minusDays(4);
    List<Tweet> tweets = new ArrayList<>();
    tweets.add(createTweet(dtf.print(fourDaysAgo), null, null, null, null));

    List<TimelineItem> results = TimelineConverter.fromTweets(tweets, now);

    assertThat(results.get(0).getCreatedAt(), is(equalTo("4d")));
}
 
Example 7
Source Project: nomulus   File: HostDeleteFlowTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_unauthorizedClientReadFromTransferredSuperordinate() {
  sessionMetadata.setClientId("NewRegistrar");
  createTld("tld");
  // Setup a transfer that should have been server approved a day ago.
  DateTime now = clock.nowUtc();
  DateTime requestTime = now.minusDays(1).minus(Registry.DEFAULT_AUTOMATIC_TRANSFER_LENGTH);
  DateTime transferExpirationTime = now.minusDays(1);
  DomainBase domain =
      persistResource(
          newDomainBase("example.tld")
              .asBuilder()
              .setPersistedCurrentSponsorClientId("NewRegistrar") // Shouldn't help.
              .addStatusValue(StatusValue.PENDING_TRANSFER)
              .setTransferData(
                  new DomainTransferData.Builder()
                      .setTransferStatus(TransferStatus.PENDING)
                      .setGainingClientId("TheRegistrar")
                      .setTransferRequestTime(requestTime)
                      .setLosingClientId("NewRegistrar")
                      .setPendingTransferExpirationTime(transferExpirationTime)
                      .build())
              .build());
  persistResource(
      newHostResource("ns1.example.tld")
          .asBuilder()
          .setPersistedCurrentSponsorClientId("NewRegistrar") // Shouldn't help.
          .setSuperordinateDomain(domain.createVKey())
          .build());
  EppException thrown = assertThrows(ResourceNotOwnedException.class, this::runFlow);
  assertAboutEppExceptions().that(thrown).marshalsToXml();
}
 
Example 8
Source Project: bateman   File: TimeSeriesTest.java    License: MIT License 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    today = new DateTime();
    yesterday = today.minusDays(1);
    twoDaysAgo = today.minusDays(2);

    prices = new TreeMap<DateTime, BigDecimal>();
    prices.put(today, new BigDecimal(9.0));
    prices.put(yesterday, new BigDecimal(11.0));
    prices.put(twoDaysAgo, new BigDecimal(10.0));

    series = new TimeSeries(prices);
}
 
Example 9
Source Project: hudi   File: HiveUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static long countRecords(String jdbcUrl, HoodieTableMetaClient source, String srcDb, int partitions,
    String user, String pass) throws SQLException {
  DateTime dateTime = DateTime.now();
  String endDateStr = dateTime.getYear() + "-" + String.format("%02d", dateTime.getMonthOfYear()) + "-"
      + String.format("%02d", dateTime.getDayOfMonth());
  dateTime = dateTime.minusDays(partitions);
  String startDateStr = dateTime.getYear() + "-" + String.format("%02d", dateTime.getMonthOfYear()) + "-"
      + String.format("%02d", dateTime.getDayOfMonth());
  System.out.println("Start date " + startDateStr + " and end date " + endDateStr);
  return countRecords(jdbcUrl, source, srcDb, startDateStr, endDateStr, user, pass);
}
 
Example 10
Source Project: nomulus   File: DomainBaseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testClone_transferDuringAutorenew() {
  // When the domain is an an autorenew grace period, we should not extend the registration
  // expiration by a further year--it should just be whatever the autorenew was
  DateTime now = DateTime.now(UTC);
  DateTime transferExpirationTime = now.minusDays(1);
  DateTime previousExpiration = now.minusDays(2);

  DomainTransferData transferData =
      new DomainTransferData.Builder()
          .setPendingTransferExpirationTime(transferExpirationTime)
          .setTransferStatus(TransferStatus.PENDING)
          .setGainingClientId("TheRegistrar")
          .setServerApproveAutorenewEvent(VKey.from(recurringBillKey))
          .setServerApproveBillingEvent(VKey.from(oneTimeBillKey))
          .build();
  domain =
      persistResource(
          domain
              .asBuilder()
              .setRegistrationExpirationTime(previousExpiration)
              .setGracePeriods(
                  ImmutableSet.of(
                      GracePeriod.createForRecurring(
                          GracePeriodStatus.AUTO_RENEW,
                          now.plusDays(1),
                          "NewRegistrar",
                          recurringBillKey)))
              .setTransferData(transferData)
              .setAutorenewBillingEvent(recurringBillKey)
              .build());
  DomainBase clone = domain.cloneProjectedAtTime(now);
  assertThat(clone.getRegistrationExpirationTime())
      .isEqualTo(domain.getRegistrationExpirationTime().plusYears(1));
  // Transferring removes the AUTORENEW grace period and adds a TRANSFER grace period
  assertThat(getOnlyElement(clone.getGracePeriods()).getType())
      .isEqualTo(GracePeriodStatus.TRANSFER);
}
 
Example 11
/**
 * Replace date formats with the DateTime values passed in.
 *
 * Operations like "YYYYMMdd-1D" are supported for doing simple subtraction
 * on the passed in DateTime.
 *
 * See DateMod for supported modification values.
 *
 * @param aQuery - a String that's modified by doing replacement according to the formats specified
 * @param replaceWith - the DateTime moment for which the replacements are based off of
 */
public static String replaceDateValues(String aQuery, DateTime replaceWith) {
  Matcher matcher = DATE_REPLACE_PATTERN.matcher(aQuery);
  while (matcher.find()) {
    final String format = matcher.group(1);
    DateTimeFormatter formatter = QueryReplaceUtil.makeDateTimeFormat(format);
    if (matcher.groupCount() > 3 &&
        matcher.group(3) != null && matcher.group(4) != null) {
      int count = Integer.valueOf(matcher.group(3));
      DateMod dm = DateMod.valueOf(matcher.group(4));
      DateTime toMod = new DateTime(replaceWith);

      if (dm.equals(DateMod.H)) {
        toMod = toMod.minusHours(count);
      } else if (dm.equals(DateMod.D)) {
        toMod = toMod.minusDays(count);
      } else if (dm.equals(DateMod.M)) {
        toMod = toMod.minusMonths(count);
      }

      aQuery = aQuery.replace(matcher.group(), formatter.print(toMod));
    } else { // no mod
      aQuery = aQuery.replace(matcher.group(), formatter.print(replaceWith));
    }
    matcher = DATE_REPLACE_PATTERN.matcher(aQuery);
  }
  return aQuery;
}
 
Example 12
private DateTime getTrainingStartTime(DateTime windowStart) {
  DateTime trainStart;
  if (isMultiDayGranularity()) {
    trainStart = windowStart.minusDays(timeGranularity.getSize() * LOOKBACK);
  } else if (this.monitoringGranularity.endsWith(TimeGranularity.MONTHS)) {
    trainStart = windowStart.minusMonths(LOOKBACK);
  } else if (this.monitoringGranularity.endsWith(TimeGranularity.WEEKS)) {
    trainStart = windowStart.minusWeeks(LOOKBACK);
  } else {
    trainStart = windowStart.minusDays(LOOKBACK);
  }
  return trainStart;
}
 
Example 13
Source Project: gocd   File: TimeConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldReturn() {
    DateTime now = new DateTime();
    DateTime yesterday = now.minusDays(1);
    assertEquals(new TimeConverter.ConvertedTime(TimeConverter.getHumanReadableDate(now)),
            timeConverter
                    .getConvertedTime(now.toDate(), yesterday.toDate()));
}
 
Example 14
Source Project: nomulus   File: HostDeleteFlowTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_authorizedClientReadFromTransferredSuperordinate() throws Exception {
  sessionMetadata.setClientId("NewRegistrar");
  createTld("tld");
  // Setup a transfer that should have been server approved a day ago.
  DateTime now = clock.nowUtc();
  DateTime requestTime = now.minusDays(1).minus(Registry.DEFAULT_AUTOMATIC_TRANSFER_LENGTH);
  DateTime transferExpirationTime = now.minusDays(1);
  DomainBase domain =
      persistResource(
          newDomainBase("example.tld")
              .asBuilder()
              .setPersistedCurrentSponsorClientId("NewRegistrar") // Shouldn't hurt.
              .addStatusValue(StatusValue.PENDING_TRANSFER)
              .setTransferData(
                  new DomainTransferData.Builder()
                      .setTransferStatus(TransferStatus.PENDING)
                      .setGainingClientId("NewRegistrar")
                      .setTransferRequestTime(requestTime)
                      .setLosingClientId("TheRegistrar")
                      .setPendingTransferExpirationTime(transferExpirationTime)
                      .build())
              .build());
  persistResource(
      newHostResource("ns1.example.tld")
          .asBuilder()
          .setPersistedCurrentSponsorClientId("TheRegistrar") // Shouldn't hurt.
          .setSuperordinateDomain(domain.createVKey())
          .build());
  clock.advanceOneMilli();
  runFlowAssertResponse(loadFile("host_delete_response.xml"));
}
 
Example 15
@Scheduled(cron="0 0 9 ? * 1,4")
@Transactional(readOnly=true)
public void sendPieceDigestEmails() {
    logger.info("Sending email digests started");
    DateTime now = new DateTime();
    DateTime minusTwoDays = now.minusDays(2);
    List<Piece> pieces = pieceDao.getPiecesInRange(minusTwoDays, now);
    Collections.shuffle(pieces);
    final List<Piece> includedPieces = new ArrayList<>(pieces.subList(0, Math.min(pieces.size(), 3)));
    if (includedPieces.isEmpty()) {
        return;
    }
    // for now - using the same data for all users. TODO send personalized selection
    final EmailDetails baseDetails = new EmailDetails();
    baseDetails.setMessageTemplate("digest.vm");
    baseDetails.setSubject("Computoser-generated tracks digest for you");
    Map<String, Object> model = Maps.newHashMap();
    baseDetails.setMessageTemplateModel(model);
    baseDetails.setFrom(from);
    baseDetails.setHtml(true);
    userDao.performBatched(User.class, 100, new PageableOperation<User>() {
        @Override
        public void execute() {
            for (User user : getData()) {
                if (user.isReceiveDailyDigest() && StringUtils.isNotBlank(user.getEmail())) {
                    EmailDetails email = SerializationUtils.clone(baseDetails);
                    email.setTo(user.getEmail());
                    email.setCurrentUser(user);
                    String hmac = SecurityUtils.hmac(user.getEmail(), hmacKey);
                    email.getMessageTemplateModel().put("pieces", includedPieces);
                    email.getMessageTemplateModel().put("hmac", hmac);
                    // needed due to SES restrictions
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new IllegalStateException(e);
                    }
                    emailService.send(email);
                }
            }
        }
    });
}
 
Example 16
Source Project: spork   File: AugmentBaseDataVisitor.java    License: Apache License 2.0 4 votes vote down vote up
Object GetSmallerValue(Object v) {
    byte type = DataType.findType(v);

    if (type == DataType.BAG || type == DataType.TUPLE
            || type == DataType.MAP)
        return null;

    switch (type) {
    case DataType.CHARARRAY:
        String str = (String) v;
        if (str.length() > 0)
            return str.substring(0, str.length() - 1);
        else
            return null;
    case DataType.BYTEARRAY:
        DataByteArray data = (DataByteArray) v;
        if (data.size() > 0)
            return new DataByteArray(data.get(), 0, data.size() - 1);
        else
            return null;
    case DataType.INTEGER:
        return Integer.valueOf((Integer) v - 1);
    case DataType.LONG:
        return Long.valueOf((Long) v - 1);
    case DataType.FLOAT:
        return Float.valueOf((Float) v - 1);
    case DataType.DOUBLE:
        return Double.valueOf((Double) v - 1);
    case DataType.BIGINTEGER:
        return ((BigInteger)v).subtract(BigInteger.ONE);
    case DataType.BIGDECIMAL:
        return ((BigDecimal)v).subtract(BigDecimal.ONE);
    case DataType.DATETIME:
        DateTime dt = (DateTime) v;
        if (dt.getMillisOfSecond() != 0) {
            return dt.minusMillis(1);
        } else if (dt.getSecondOfMinute() != 0) {
            return dt.minusSeconds(1);
        } else if (dt.getMinuteOfHour() != 0) {
            return dt.minusMinutes(1);
        } else if (dt.getHourOfDay() != 0) {
            return dt.minusHours(1);
        } else {
            return dt.minusDays(1);
        }
    default:
        return null;
    }

}
 
Example 17
Source Project: docusign-java-client   File: SdkUnitTests.java    License: MIT License 4 votes vote down vote up
private String[] getLastTenEnvelopeIds() {
	String [] envelopeIds = new String[0];

	ApiClient apiClient = new ApiClient(BaseUrl);
	//String currentDir = System.getProperty("user.dir");

	try {
		// IMPORTANT NOTE:
		// the first time you ask for a JWT access token, you should grant access by making the following call
		// get DocuSign OAuth authorization url:
		//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
		// open DocuSign OAuth authorization url in the browser, login and grant access
		//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
		// END OF NOTE

		java.util.List<String> scopes = new ArrayList<String>();
		scopes.add(OAuth.Scope_SIGNATURE);

		OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
		Assert.assertNotSame(null, oAuthToken);
		// now that the API client has an OAuth token, let's use it in all
		// DocuSign APIs
		apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
		UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
		Assert.assertNotSame(null, userInfo);
		Assert.assertNotNull(userInfo.getAccounts());
		Assert.assertTrue(userInfo.getAccounts().size() > 0);

		// parse first account's baseUrl
		// below code required for production, no effect in demo (same
		// domain)
		apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
		Configuration.setDefaultApiClient(apiClient);
		String accountId = userInfo.getAccounts().get(0).getAccountId();

		// This example gets statuses of all envelopes in your account going back 1 full month...
		DateTime fromDate = new DateTime();
		fromDate = fromDate.minusDays(30);
		String fromDateStr = fromDate.toString("yyyy-MM-dd");

		// set a filter for the envelopes we want returned using the fromDate and count properties
		EnvelopesApi envelopesApi = new EnvelopesApi();
		EnvelopesApi.ListStatusChangesOptions listStatusChangesOptions = envelopesApi.new ListStatusChangesOptions();
		listStatusChangesOptions.setCount("10");
		listStatusChangesOptions.setFromDate(fromDateStr);

		// |EnvelopesApi| contains methods related to envelopes and envelope recipients
		EnvelopesInformation envelopesInformation = envelopesApi.listStatusChanges(accountId, listStatusChangesOptions);

		Assert.assertNotNull(envelopesInformation);
		Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0));
		Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0).getEnvelopeId());
		Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0).getStatus());

		List<Envelope> envelopes = envelopesInformation.getEnvelopes();
		envelopeIds = new String[envelopes.size()];
		for (int i = 0; i < envelopes.size(); i++){
			envelopeIds[i] = envelopes.get(i).getEnvelopeId();
		}
	} catch (ApiException ex) {
		Assert.fail("Exception: " + ex);
	} catch (Exception e) {
		e.printStackTrace();
		Assert.fail("Exception: " + e.getLocalizedMessage());
	}

	return envelopeIds;
}
 
Example 18
@Override
public void setUpTest()
{
    organisationUnit = createOrganisationUnit( 'A' );
    organisationUnitService.addOrganisationUnit( organisationUnit );

    OrganisationUnit organisationUnitB = createOrganisationUnit( 'B' );
    organisationUnitService.addOrganisationUnit( organisationUnitB );

    entityInstanceAttribute = createTrackedEntityAttribute( 'A' );
    attributeService.addTrackedEntityAttribute( entityInstanceAttribute );

    entityInstanceA1 = createTrackedEntityInstance( organisationUnit );
    entityInstanceB1 = createTrackedEntityInstance( organisationUnit );
    entityInstanceB1.setUid( "UID-B1" );

    programA = createProgram( 'A', new HashSet<>(), organisationUnit );

    programService.addProgram( programA );

    ProgramStage stageA = createProgramStage( 'A', programA );
    stageA.setSortOrder( 1 );
    programStageService.saveProgramStage( stageA );

    Set<ProgramStage> programStages = new HashSet<>();
    programStages.add( stageA );
    programA.setProgramStages( programStages );
    programService.updateProgram( programA );

    DateTime enrollmentDate = DateTime.now();
    enrollmentDate.withTimeAtStartOfDay();
    enrollmentDate = enrollmentDate.minusDays( 70 );

    DateTime incidenDate = DateTime.now();
    incidenDate.withTimeAtStartOfDay();

    programInstanceA = new ProgramInstance( enrollmentDate.toDate(), incidenDate.toDate(), entityInstanceA1,
        programA );
    programInstanceA.setUid( "UID-A" );
    programInstanceA.setOrganisationUnit( organisationUnit );

    programStageInstanceA = new ProgramStageInstance( programInstanceA, stageA );
    programInstanceA.setUid( "UID-PSI-A" );
    programInstanceA.setOrganisationUnit( organisationUnit );
}
 
Example 19
/**
 * Returns a data frame containing the same time daily data, based on input time
 * @param originalDF the original dataframe
 * @param time the prediction time, in unix timestamp
 * @return DataFrame containing same time of daily data for LOOKBACK number of days
 */
private DataFrame getDailyDF(DataFrame originalDF, Long time, String timezone) {
  LongSeries longSeries = (LongSeries) originalDF.get(COL_TIME);
  long start = longSeries.getLong(0);
  DateTime dt = new DateTime(time).withZone(DateTimeZone.forID(timezone));
  DataFrame df = DataFrame.builder(COL_TIME, COL_VALUE).build();

  for (int i = 0; i < LOOKBACK; i++) {
    DateTime subDt = dt.minusDays(1);
    long t = subDt.getMillis();
    if (t < start) {
      break;
    }
    int index = longSeries.find(t);
    if (index != -1) {
      df = df.append(originalDF.slice(index, index + 1));
    } else {
      int backtrackCounter = 0;
      // If the 1 day look back data doesn't exist, use the data one period before till backtrackCounter greater than 4
      while (index == -1 && backtrackCounter <= 4) {
        subDt = subDt.minusDays(period);
        long timestamp = subDt.getMillis();
        index = longSeries.find(timestamp);
        backtrackCounter++;
      }

      if (index != -1) {
        df = df.append(originalDF.slice(index, index + 1));
      } else {
        // If not found value up to 4 weeks, insert the last value
        double lastVal = (originalDF.get(COL_VALUE)).getDouble(longSeries.find(dt.getMillis()));
        DateTime nextDt = dt.minusDays(1);
        DataFrame appendDf = DataFrame.builder(COL_TIME, COL_VALUE).append(nextDt, lastVal).build();
        df = df.append(appendDf);
      }
    }
    dt = dt.minusDays(1);
  }
  df = df.reverse();
  return df;
}
 
Example 20
@Test
public void subtract_days_from_date_in_java_joda () {
	
	DateTime superBowlXLV = new DateTime(2011, 2, 6, 0, 0, 0, 0);
	DateTime pregame = superBowlXLV.minusDays(1);

	DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");
	
	logger.info(superBowlXLV.toString(fmt));
	logger.info(pregame.toString(fmt));

	assertTrue(pregame.isBefore(superBowlXLV));
}