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

The following examples show how to use org.joda.time.DateTime#minusHours() . 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: ShoppingListServiceImpl.java    From privacy-friendly-shopping-list with Apache License 2.0 6 votes vote down vote up
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 File: OrganizationReportGenerator.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
private TimePeriod getTimePeriod(int noOfHours) throws MegatronException {
        // DEBUG
//        try {
//            Date startDate = DateUtil.parseDateTime(DateUtil.DATE_TIME_FORMAT_WITH_SECONDS, "2013-01-01 00:00:00");
//            Date endDate = DateUtil.parseDateTime(DateUtil.DATE_TIME_FORMAT_WITH_SECONDS, "2014-01-01 23:59:59");
//            return new TimePeriod(startDate, endDate);
//        } catch (ParseException e) {
//            throw new MegatronException("Cannot parse date.", e);
//        }
        
        DateTime now = new DateTime();
        DateTime endDateTime = now.hourOfDay().roundFloorCopy();
        DateTime startDateTime = endDateTime.minusHours(noOfHours);
        // set end time to 23:59:59
        Date endDate = endDateTime.toDate();
        endDate.setTime(endDate.getTime() - 1000L);
        return new TimePeriod(startDateTime.toDate(), endDate);
    }
 
Example 3
Source File: QueryReplaceUtil.java    From chronos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 4
Source File: TimelineConverterTest.java    From twittererer with Apache License 2.0 5 votes vote down vote up
@Test
public void fromTweetsMapAgeHours() {
    DateTime now = DateTime.now();
    DateTime twoHoursAgo = now.minusHours(2);
    List<Tweet> tweets = new ArrayList<>();
    tweets.add(createTweet(dtf.print(twoHoursAgo), null, null, null, null));

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

    assertThat(results.get(0).getCreatedAt(), is(equalTo("2h")));
}
 
Example 5
Source File: Session.java    From conference-app with MIT License 5 votes vote down vote up
/**
 * Method defines if session is near to be started or finished +/- 1 hour
 * 
 * @param now
 * @return true if session will start in +/- 1 hour from now
 */
public boolean isInNearProgress(DateTime now) {
    DateTime startTime = DateTime.parse(this.date + " " + this.start, DateTimeFormat.forPattern("dd.MM.yyyy HH:mm"));
    DateTime beforeStart = now.minusHours(1);
    DateTime afterStart = now.plusHours(2);
    return ((startTime.isAfter(beforeStart) || startTime.isEqual(beforeStart)) && (startTime.isBefore(afterStart) || startTime.isEqual(afterStart)));
}
 
Example 6
Source File: SchedulerTest.java    From celos with Apache License 2.0 5 votes vote down vote up
/**
 * Create a workflow with a hourly schedule and an always trigger.
 *
 * Step the workflow a single time.
 *
 * Ensure that all hourly slots have been changed to ready.
 */
@Test
public void updatesWaitingSlotsToReady() throws Exception {
    WorkflowID wfID1 = new WorkflowID("wf1");
    Schedule sch1 = makeHourlySchedule();
    SchedulingStrategy str1 = makeSerialSchedulingStrategy();
    Trigger tr1 = makeAlwaysTrigger();
    ExternalService srv1 = new MockExternalService(new MockExternalService.MockExternalStatusRunning());
    int maxRetryCount = 0;
    Workflow wf1 = new Workflow(wfID1, sch1, str1, tr1, srv1, maxRetryCount, Workflow.DEFAULT_START_TIME, Workflow.DEFAULT_WAIT_TIMEOUT_SECONDS, emptyWorkflowInfo);

    WorkflowConfiguration cfg = new WorkflowConfiguration();
    cfg.addWorkflow(wf1);

    int slidingWindowHours = 24;
    DateTime current = DateTime.parse("2013-11-27T15:01Z");
    DateTime currentFullHour = Util.toFullHour(current);

    Scheduler sched = new Scheduler(cfg, slidingWindowHours);
    sched.step(new ScheduledTime(current), connection);

    Assert.assertEquals(slidingWindowHours, connection.size());

    for (int i = 0; i < slidingWindowHours; i++) {
        SlotID id = new SlotID(wfID1, new ScheduledTime(currentFullHour.minusHours(i)));
        SlotState state = connection.getSlotState(id);
        if (state == null) {
            throw new AssertionError("Slot " + id + " not found.");
        }
        Assert.assertEquals(SlotState.Status.READY, state.getStatus());
    }

}
 
Example 7
Source File: RecentEventsReportJob.java    From AisAbnormal with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * The execute method is triggered by the scheduler, when the report should be generated.
 *
 * @param jobExecutionContext
 * @throws JobExecutionException
 */
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    LOG.debug("RecentEventsReportJob triggered");

    DateTime t2 = new DateTime();
    DateTime t1 = lastRun >= 0 ? new DateTime(lastRun) : t2.minusHours(24);
    lastRun = t2.getMillis();

    Multimap<Class<? extends Event>, Event> eventsByType = getEventsByType(t1.toDate(), t2.toDate());
    String reportBody = generateReportBody(t1.toDate(), t2.toDate(), eventsByType);
    reportMailer.send("Abnormal events", reportBody);

    LOG.debug("RecentEventsReportJob finished");
}
 
Example 8
Source File: SagerCasterBinding.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
protected HistoricItem getPreviousValue(Item theItem) {
    DateTime now = new DateTime();
    AbstractInstant earlier = now.minusHours(6);
    if (persistenceService == null) {
        return PersistenceExtensions.historicState(theItem, earlier);
    } else {
        return PersistenceExtensions.historicState(theItem, earlier, persistenceService);
    }
}
 
Example 9
Source File: SuplLppClientHelper.java    From supl-client with Apache License 2.0 4 votes vote down vote up
/**
 * Builds a {@link GloEphemeris} instance for the GLONASS satellite from the {@link
 * GNSS_NavModelSatelliteElement} instance containing ephemeris parameters, the reference date
 * {@code DateTime} in Moscow time, and a map with svid as keys and frequency number as values.
 */
private static GloEphemeris buildGloEphemeris(
    GNSS_NavModelSatelliteElement element,
    DateTime moscowDate,
    Map<Integer, Integer> svidToFreqNumMap) {
  GLONASS_ClockModel clock = element.getGnss_ClockModel().getGlonass_ClockModel();
  NavModel_GLONASS_ECEF orbit = element.getGnss_OrbitModel().getGlonass_ECEF();

  // Gets the time of ephemeris, and converts it to UTC time zone.
  // Time of day (minutes) in UTC(SU)
  int iodMin =
      convertBitSetToInt(element.getIod().getValue()) * LppConstants.LPP_GLO_IOD_SCALE_FACTOR;
  DateTime moscowTimeOfEph =
      new DateTime(
          moscowDate.getYear(),
          moscowDate.getMonthOfYear(),
          moscowDate.getDayOfMonth(),
          iodMin / 60,
          iodMin % 60,
          DateTimeZone.UTC);
  DateTime utcTimeOfEph = moscowTimeOfEph.minusHours(TimeConstants.MOSCOW_UTC_TIME_OFFSET_HOURS);

  int svid = element.getSvID().getSatellite_id().getInteger().intValue() + 1;
  int carrierFreqNum = svidToFreqNumMap.get(svid);

  return GloEphemeris.newBuilder()
      .setFreqNum(carrierFreqNum)
      .setSvid(svid)
      .setUtcTime(utcTimeOfEph)
      .setHealth(element.getSvHealth().getValue().get(1) ? 1 : 0)
      .setBiasS(clock.getGloTau().getInteger().intValue() * ScaleFactors.GLO_CLK_TAU)
      .setRelFreqBias(clock.getGloGamma().getInteger().intValue() * ScaleFactors.GLO_CLK_GAMMA)
      .setAgeDays(orbit.getGloEn().getInteger().intValue())
      .setXSatPosM(
          orbit.getGloX().getInteger().intValue()
              * ScaleFactors.GLO_ORB_POS_KM
              * GnssConstants.METERS_PER_KM)
      .setYSatPosM(
          orbit.getGloY().getInteger().intValue()
              * ScaleFactors.GLO_ORB_POS_KM
              * GnssConstants.METERS_PER_KM)
      .setZSatPosM(
          orbit.getGloZ().getInteger().intValue()
              * ScaleFactors.GLO_ORB_POS_KM
              * GnssConstants.METERS_PER_KM)
      .setXSatVelMps(
          orbit.getGloXdot().getInteger().intValue()
              * ScaleFactors.GLO_ORB_VEL_KMPS
              * GnssConstants.METERS_PER_KM)
      .setYSatVelMps(
          orbit.getGloYdot().getInteger().intValue()
              * ScaleFactors.GLO_ORB_VEL_KMPS
              * GnssConstants.METERS_PER_KM)
      .setZSatVelMps(
          orbit.getGloZdot().getInteger().intValue()
              * ScaleFactors.GLO_ORB_VEL_KMPS
              * GnssConstants.METERS_PER_KM)
      .setXMoonSunAccMps2(
          orbit.getGloXdotdot().getInteger().intValue()
              * ScaleFactors.GLO_ORB_ACCELERATION_KMPS2
              * GnssConstants.METERS_PER_KM)
      .setYMoonSunAccMps2(
          orbit.getGloYdotdot().getInteger().intValue()
              * ScaleFactors.GLO_ORB_ACCELERATION_KMPS2
              * GnssConstants.METERS_PER_KM)
      .setZMoonSunAccMps2(
          orbit.getGloZdotdot().getInteger().intValue()
              * ScaleFactors.GLO_ORB_ACCELERATION_KMPS2
              * GnssConstants.METERS_PER_KM)
      .build();
}
 
Example 10
Source File: ExclusiveJobWrapperAT.java    From nakadi with MIT License 4 votes vote down vote up
private void createLatestNode(final int hoursAgo) throws Exception {
    final DateTime now = new DateTime(DateTimeZone.UTC);
    final DateTime pastDate = now.minusHours(hoursAgo);
    final byte[] data = objectMapper.writeValueAsString(pastDate).getBytes(Charsets.UTF_8);
    CURATOR.create().creatingParentsIfNeeded().forPath(latestPath, data);
}
 
Example 11
Source File: FileSystemUtils.java    From Cubert with Apache License 2.0 4 votes vote down vote up
public static List<Path> getDurationPaths(FileSystem fs,
                                          Path root,
                                          DateTime startDate,
                                          DateTime endDate,
                                          boolean isDaily,
                                          int hourStep,
                                          boolean errorOnMissing,
                                          boolean useHourlyForMissingDaily) throws IOException
{
    List<Path> paths = new ArrayList<Path>();
    while (endDate.compareTo(startDate) >= 0) {
        Path loc;
        if (isDaily)
            loc = generateDatedPath(root, endDate.getYear(), endDate.getMonthOfYear(), endDate.getDayOfMonth());
        else
            loc = generateDatedPath(root, endDate.getYear(), endDate.getMonthOfYear(), endDate.getDayOfMonth(),
                    endDate.getHourOfDay());

        // Check that directory exists, and contains avro files.
        if (fs.exists(loc) && fs.globStatus(new Path(loc, "*" + "avro")).length > 0) {
            paths.add(loc);
        }

        else {

            loc = generateDatedPath(new Path(root.getParent(),"hourly"), endDate.getYear(),
                    endDate.getMonthOfYear(), endDate.getDayOfMonth());
            if(isDaily && useHourlyForMissingDaily && fs.exists(loc))
            {
                  for (FileStatus hour: fs.listStatus(loc)) {
                      paths.add(hour.getPath());
                  }
            }

            else if (errorOnMissing) {
                throw new RuntimeException("Missing directory " + loc.toString());
            }

        }
        if (hourStep ==24)
            endDate = endDate.minusDays(1);
        else
            endDate = endDate.minusHours(hourStep);
    }
    return paths;
}
 
Example 12
Source File: AugmentBaseDataVisitor.java    From spork with 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 13
Source File: DateMinusHours.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void subtract_hours_from_date_in_java_with_joda () {
	
	DateTime newYearsDay = new DateTime(2013, 1, 1, 0, 0, 0, 0);
	DateTime newYearsEve = newYearsDay.minusHours(1);

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

	assertTrue(newYearsEve.isBefore(newYearsDay));
}