Java Code Examples for org.joda.time.DateTime#minusDays()
The following examples show how to use
org.joda.time.DateTime#minusDays() .
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: DateHelper.java From secure-data-service with Apache License 2.0 | 6 votes |
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 2
Source File: ShoppingListServiceImpl.java From privacy-friendly-shopping-list with Apache License 2.0 | 6 votes |
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 3
Source File: HiveUtil.java From hudi with Apache License 2.0 | 5 votes |
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 4
Source File: HostDeleteFlowTest.java From nomulus with Apache License 2.0 | 5 votes |
@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 5
Source File: TimeConverterTest.java From gocd with Apache License 2.0 | 5 votes |
@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 6
Source File: HoltWintersDetector.java From incubator-pinot with Apache License 2.0 | 5 votes |
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 7
Source File: QueryReplaceUtil.java From chronos with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * 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 8
Source File: DomainBaseTest.java From nomulus with Apache License 2.0 | 5 votes |
@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 9
Source File: EsRestClientContainer.java From frostmourne with MIT License | 5 votes |
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 10
Source File: TimeSeriesTest.java From bateman with MIT License | 5 votes |
@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 11
Source File: HostDeleteFlowTest.java From nomulus with Apache License 2.0 | 5 votes |
@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 12
Source File: TimelineConverterTest.java From twittererer with Apache License 2.0 | 5 votes |
@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 13
Source File: AbstractSameTimeMetric.java From frostmourne with MIT License | 5 votes |
/** * 根据结束时间和比较间隔类型获取开始时间 * * @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 14
Source File: StatisticsXmlReportGenerator.java From megatron-java with Apache License 2.0 | 5 votes |
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 15
Source File: SdkUnitTests.java From docusign-java-client with MIT License | 4 votes |
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 16
Source File: TrackedEntityInstanceServiceTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
@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 17
Source File: AugmentBaseDataVisitor.java From spork with Apache License 2.0 | 4 votes |
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 18
Source File: PieceDigestSendingJob.java From computoser with GNU Affero General Public License v3.0 | 4 votes |
@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 19
Source File: HoltWintersDetector.java From incubator-pinot with Apache License 2.0 | 4 votes |
/** * 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
Source File: DateMinusDays.java From levelup-java-examples with Apache License 2.0 | 3 votes |
@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)); }