private void registerMockFacilityUsages(Facility facility, User user) {
   DateTime startOfDay = BASE_DATE.toDateTimeAtStartOfDay();
   facilityService.registerUtilization(
       facility.id,
       asList(
           utilize(CAR, 24, startOfDay, facility),
           utilize(CAR, 0, startOfDay.plusHours(12), facility),
           utilize(CAR, 24, startOfDay.secondOfDay().withMaximumValue(), facility),
           utilize(ELECTRIC_CAR, 2, startOfDay, facility),
           utilize(ELECTRIC_CAR, 0, startOfDay.plusHours(12), facility),
           utilize(ELECTRIC_CAR, 2, startOfDay.secondOfDay().withMaximumValue(), facility)),
       user);
 }
  @Test
  public void testMergeShiftedTimestamp() {
    Result<SearchResultValue> r1 =
        new Result<SearchResultValue>(
            currTime,
            new SearchResultValue(ImmutableList.<SearchHit>of(new SearchHit("blah", "foo"))));

    Result<SearchResultValue> r2 =
        new Result<SearchResultValue>(
            currTime.plusHours(2),
            new SearchResultValue(ImmutableList.<SearchHit>of(new SearchHit("blah2", "foo2"))));

    Result<SearchResultValue> expected =
        new Result<SearchResultValue>(
            currTime,
            new SearchResultValue(
                ImmutableList.<SearchHit>of(
                    new SearchHit("blah", "foo"), new SearchHit("blah2", "foo2"))));

    Result<SearchResultValue> actual =
        new SearchBinaryFn(
                new LexicographicSearchSortSpec(), QueryGranularity.ALL, Integer.MAX_VALUE)
            .apply(r1, r2);
    Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp());
    assertSearchMergeResult(expected.getValue(), actual.getValue());
  }
  private void generateTimeComparisons(List<String> timeZoneIds) {
    mDisplayLists.clear();

    // Cache timezone objects
    DateTimeZone[] timeZones = new DateTimeZone[timeZoneIds.size()];
    for (int i = 0; i < timeZoneIds.size(); i++) {
      timeZones[i] = DateTimeZone.forID(timeZoneIds.get(i));
    }

    // Round current time down to the hour
    DateTime dateTime =
        new DateTime().withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);

    // format to local date/time (shorten for more comparisons)
    mDateTimeFormatter =
        timeZones.length < 3 ? DateTimeFormat.shortDateTime() : DateTimeFormat.shortTime();

    // Iterate over the next n hours
    for (int i = 0; i < DISPLAY_HOURS; i++) {
      List<String> displayList = new ArrayList<String>();
      for (DateTimeZone dateTimeZone : timeZones) {
        displayList.add(dateTime.withZone(dateTimeZone).toString(mDateTimeFormatter));
      }
      mDisplayLists.add(displayList);
      dateTime = dateTime.plusHours(1);
    }
  }
  @Test
  public void test_aggregationByDay() throws Exception {
    DateTimeZone utc = DateTimeZone.UTC;
    DateTime startDate = new DateTime(2014, 1, 1, 0, 0, utc);
    DateTime endDate = new DateTime(2014, 1, 3, 3, 0, utc);
    ListDataPointGroup group = new ListDataPointGroup("aggregationByDay");

    for (DateTime hour = startDate; hour.isBefore(endDate); hour = hour.plusHours(1)) {
      group.addDataPoint(new LongDataPoint(hour.getMillis(), 1L));
    }

    SumAggregator aggregator = new SumAggregator(new DoubleDataPointFactoryImpl());
    aggregator.setSampling(new Sampling(1, TimeUnit.DAYS));
    aggregator.setAlignSampling(false);

    DataPointGroup dayCount = aggregator.aggregate(group);

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(24L));

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(24L));

    assertThat(dayCount.hasNext(), is(true));
    assertThat(dayCount.next().getLongValue(), is(3L));

    assertThat(dayCount.hasNext(), is(false));
  }
Exemple #5
0
 private DateTime ensureSameDate(
     DateTime date,
     int years,
     int monthsOfYear,
     int dayOfMonth,
     int hoursOfDay,
     int minutesOfHour,
     int secondsOfMinute,
     DateTimeZone timeZone) {
   if (date.getSecondOfMinute() != secondsOfMinute) {
     date = date.plusSeconds(secondsOfMinute - date.getSecondOfMinute());
   }
   if (date.getMinuteOfHour() != minutesOfHour) {
     date = date.plusMinutes(minutesOfHour - date.getMinuteOfHour());
   }
   if (date.getHourOfDay() != hoursOfDay) {
     date = date.plusHours(hoursOfDay - date.getHourOfDay());
   }
   if (date.getDayOfMonth() != dayOfMonth) {
     date = date.plusDays(dayOfMonth - date.getDayOfMonth());
   }
   if (date.getMonthOfYear() != monthsOfYear) {
     date = date.plusMonths(monthsOfYear - date.getMonthOfYear());
   }
   if (date.getYear() != years) {
     date = date.plusYears(years - date.getYear());
   }
   return date;
 }
Exemple #6
0
  public static DateTime nextExecution(int hour, int minute) {
    DateTime next =
        new DateTime()
            .withHourOfDay(hour)
            .withMinuteOfHour(minute)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0);

    return (next.isBeforeNow()) ? next.plusHours(24) : next;
  }
 /**
  * We need the number of days rather than the number of elapsed milliseconds divided by the number
  * in a day - timezone changes ete... To avoid confusion about what constitutes a full day we
  * count the number of lunchtimes (noon).
  *
  * @param start
  * @param end
  * @return
  */
 private int countDays(DateTime start, DateTime end) {
   int count = 0;
   Assert.assertEquals(start.getHourOfDay(), 0);
   Assert.assertEquals(start.getMinuteOfHour(), 0);
   start = start.plusHours(12);
   while (start.isBefore(end)) {
     count++;
     start = start.plusDays(1);
   }
   return count;
 }
 private void prepareIndex(DateTime date, int numHours, int stepSizeHours, int idxIdStart)
     throws IOException, InterruptedException, ExecutionException {
   IndexRequestBuilder[] reqs = new IndexRequestBuilder[numHours];
   for (int i = idxIdStart; i < idxIdStart + reqs.length; i++) {
     reqs[i - idxIdStart] =
         client()
             .prepareIndex("idx2", "type", "" + i)
             .setSource(jsonBuilder().startObject().field("date", date).endObject());
     date = date.plusHours(stepSizeHours);
   }
   indexRandom(true, reqs);
 }
Exemple #9
0
  public static void main(String[] args) throws Exception {
    // test day init and print to string
    DateTime fooDateTime = new DateTime(1978, 6, 1, 12, 10, 8, 0);
    System.out.println(fooDateTime.toString("yyyy-MM-dd HH:mm:ss")); // "1978-06-01 12:10:08"

    // test minus/plus and years/days between function
    DateTime now = new DateTime();
    DateTime nowLater = now.plusHours(22);
    DateTime tomorrow = now.plusHours(25);
    System.out.println(isSameDay(now, nowLater)); // true
    System.out.println(isSameDay(now, tomorrow)); // false

    DateTime oneYearsAgo = now.minusYears(2).plusDays(20);
    DateTime twoYearsAgo = now.minusYears(2);
    System.out.println(getAge(oneYearsAgo)); // 1
    System.out.println(getAge(twoYearsAgo)); // 2
  }
  @Test(groups = "fast")
  public void testEventsForCancelledSubscriptionAfterTransfer() throws Exception {
    final DateTime subscriptionStartTime = clock.getUTCNow();
    final DateTime subscriptionCancelTime = subscriptionStartTime.plusDays(1);
    final ImmutableList<ExistingEvent> existingEvents =
        ImmutableList.<ExistingEvent>of(
            createEvent(subscriptionStartTime, SubscriptionTransitionType.CREATE),
            createEvent(subscriptionCancelTime, SubscriptionTransitionType.CANCEL));
    final SubscriptionBuilder subscriptionBuilder = new SubscriptionBuilder();
    final SubscriptionData subscription = new SubscriptionData(subscriptionBuilder);

    final DateTime transferDate = subscriptionStartTime.plusHours(1);
    final List<EntitlementEvent> events =
        transferApi.toEvents(existingEvents, subscription, transferDate, callContext);

    Assert.assertEquals(events.size(), 1);
    Assert.assertEquals(events.get(0).getType(), EventType.API_USER);
    Assert.assertEquals(events.get(0).getEffectiveDate(), transferDate);
    Assert.assertEquals(((ApiEventTransfer) events.get(0)).getEventType(), ApiEventType.TRANSFER);
  }
  public static void main(String[] args) {
    //
    // Creates an instance of current DateTime which represents the
    // current date time.
    //
    DateTime dateTime = new DateTime();
    System.out.println("DateTime = " + dateTime);

    //
    // Plus some hours, minutes, and seconds to the original DateTime.
    //
    System.out.println("Plus 1 hour is " + dateTime.plusHours(1));
    System.out.println("Plus 10 minutes is " + dateTime.plusMinutes(10));
    System.out.println("Plus 60 seconds is " + dateTime.plusSeconds(60));

    //
    // Minus some hours, minutes, and seconds to the original DateTime.
    //
    System.out.println("Minus 1 hour is " + dateTime.minusHours(1));
    System.out.println("Minus 10 minutes is " + dateTime.minusMinutes(10));
    System.out.println("Minus 60 seconds is " + dateTime.minusSeconds(60));
  }
  @Test
  public void test_aggregationByHourOverMarch_dst() {
    ListDataPointGroup group = new ListDataPointGroup("March");
    DateTimeZone paris = DateTimeZone.forID("Europe/Paris");

    for (DateTime hour = new DateTime(2014, 3, 1, 0, 0, paris); // 1st of March
        hour.isBefore(new DateTime(2014, 4, 1, 0, 0, paris)); // 1st of April
        hour = hour.plusHours(1)) {
      group.addDataPoint(new LongDataPoint(hour.getMillis(), 1L));
    }

    SumAggregator aggregator = new SumAggregator(new DoubleDataPointFactoryImpl());
    aggregator.setTimeZone(paris);
    aggregator.setSampling(new Sampling(1, TimeUnit.MONTHS));
    aggregator.setAlignSampling(true);

    DataPointGroup hourCount = aggregator.aggregate(group);
    assert hourCount.hasNext();
    // 31 * 24 - 1 = 743 hours in March
    assertThat(hourCount.next().getLongValue(), is(743L));
    assertThat(hourCount.hasNext(), is(false));
  }
Exemple #13
0
  /**
   * 计算指定时间之后的日期
   *
   * @param date 待计算时间
   * @param random 待计算数
   * @param timeType 时间类型枚举
   * @see org.codingsills.modules.utils.DateKit.TimeType
   * @return Date
   */
  public static Date nextDate(Date date, int random, TimeType timeType) {
    Date nextDate = null;
    if (date == null) {
      return nextDate;
    }
    DateTime dateTime = fromDate(date);
    random = Math.abs(random);
    switch (timeType.getCode()) {
      case "Y":
        nextDate = dateTime.plusYears(random).toDate();
        break;
      case "M":
        nextDate = dateTime.plusMonths(random).toDate();
        break;
      case "W":
        nextDate = dateTime.plusWeeks(random).toDate();
        break;
      case "D":
        nextDate = dateTime.plusDays(random).toDate();
        break;
      case "H":
        nextDate = dateTime.plusHours(random).toDate();
        break;
      case "MIN":
        nextDate = dateTime.plusMinutes(random).toDate();
        break;
      case "S":
        nextDate = dateTime.plusSeconds(random).toDate();
        break;
      case "MS":
        nextDate = dateTime.plusMillis(random).toDate();
        break;
      default:
        break;
    }

    return nextDate;
  }
Exemple #14
0
  @Test
  public void shouldProperlyApplyManipulations() throws Exception {
    String string = "ala-has-a-cat";
    DateTime now = DateUtil.now();
    String toString = now.toString();
    String toStringWithPattern = now.toString("yyyy-MM-dd");
    KeyEvaluator keyEvaluator = new KeyEvaluator(null);

    String pastDate = "2015-05-15";
    String timeZone =
        new DateTime(pastDate)
            .toString("Z"); // Figure out the correct time zone for the given date and locale

    assertEquals("lower_case", keyEvaluator.manipulate("tolower", "LOWER_CASE"));
    assertEquals("UPPER_CASE", keyEvaluator.manipulate("toupper", "upper_case"));
    assertEquals("Capitalize", keyEvaluator.manipulate("capitalize", "capitalize"));
    assertEquals("My+sample+message", keyEvaluator.manipulate("urlencode", "My sample message"));
    assertEquals("37%2365%4078%2490", keyEvaluator.manipulate("URLEncode", "37#65@78$90"));
    assertEquals("67890", keyEvaluator.manipulate("substring(5)", "1234567890"));
    assertEquals("67", keyEvaluator.manipulate("substring(5,7)", "1234567890"));
    assertEquals(string, keyEvaluator.manipulate("join(-)", "ala has a cat"));
    assertEquals("ala", keyEvaluator.manipulate("split(-,0)", string));
    assertEquals("cat", keyEvaluator.manipulate("split(-,3)", string));
    assertEquals(
        pastDate + " 11:32 " + timeZone,
        keyEvaluator.manipulate("parseDate(yyyy/dd/MM hh:mm)", "2015/15/05 11:32"));
    assertEquals(toStringWithPattern, keyEvaluator.manipulate("datetime(yyyy-MM-dd)", toString));
    assertEquals(now.plusDays(1).toString(), keyEvaluator.manipulate("plusDays(1)", toString));
    assertEquals(now.minusDays(1).toString(), keyEvaluator.manipulate("minusDays(1)", toString));
    assertEquals(now.plusHours(2).toString(), keyEvaluator.manipulate("plusHours(2)", toString));
    assertEquals(now.minusHours(2).toString(), keyEvaluator.manipulate("minusHours(2)", toString));
    assertEquals(
        now.plusMinutes(20).toString(), keyEvaluator.manipulate("plusMinutes(20)", toString));
    assertEquals(
        now.minusMinutes(20).toString(), keyEvaluator.manipulate("minusMinutes(20)", toString));
  }
  // To display all the tasks today
  public ArrayList<Task> displayToday(ArrayList<Task> taskList) {
    ArrayList<Task> result = new ArrayList<Task>();
    DateTime now = new DateTime();
    DateTime startOfDay = now.withTimeAtStartOfDay();
    DateTime endOfDay = startOfDay.plusHours(24);
    for (Task task : taskList) {
      switch (task.getType()) {
        case Constants.TYPE_FLOATING:
          result.add(task);
          break;

        case Constants.TYPE_EVENT:
          if (task.getEndingTime().isBefore(endOfDay)
              && (task.getEndingTime().isAfter(startOfDay))) {
            result.add(task);
          }
          break;

        case Constants.TYPE_DEADLINE:
          if (task.getEndingTime().isBefore(endOfDay)) {
            result.add(task);
          }
          break;

        case Constants.TYPE_RECUR:
          for (DateTime date : task.getRecurDates()) {
            if (date.getDayOfYear() == now.getDayOfYear()) {
              result.add(task);
            }
          }
          break;
      }
    }

    return result;
  }
 public synchronized DateTime addHours(int hours) {
   systemDate = systemDate.plusHours(hours);
   return systemDate;
 }
 private DateTime getExpirationDate(DateTime created) {
   return created.plusHours(configurationService.getConfiguration().getLongTimeout());
 }
 public synchronized DateTime addHour() {
   systemDate = systemDate.plusHours(1);
   return systemDate;
 }
Exemple #19
0
  @Override
  public boolean nextKeyValue() throws IOException, InterruptedException {

    // we only pull for a specified time. unfinished work will be
    // rescheduled in the next
    // run.
    if (System.currentTimeMillis() > maxPullTime) {
      if (reader != null) {
        closeReader();
      }
      return false;
    }

    while (true) {
      try {
        if (reader == null || reader.hasNext() == false) {
          EtlRequest request = split.popRequest();
          if (request == null) {
            return false;
          }

          if (maxPullHours > 0) {
            endTimeStamp = 0;
          }

          key.set(
              request.getTopic(),
              request.getNodeId(),
              request.getPartition(),
              request.getOffset(),
              request.getOffset(),
              0);
          value = new AvroWrapper<Object>(new Object());

          System.out.println(
              "topic:"
                  + request.getTopic()
                  + " partition:"
                  + request.getPartition()
                  + " beginOffset:"
                  + request.getOffset()
                  + " estimatedLastOffset:"
                  + request.getLastOffset());

          statusMsg += statusMsg.length() > 0 ? "; " : "";
          statusMsg +=
              request.getTopic() + ":" + request.getNodeId() + ":" + request.getPartition();
          context.setStatus(statusMsg);

          if (reader != null) {
            closeReader();
          }
          reader =
              new KafkaReader(
                  request,
                  EtlInputFormat.getKafkaClientTimeout(mapperContext),
                  EtlInputFormat.getKafkaClientBufferSize(mapperContext));

          decoder =
              (MessageDecoder<Message, Record>)
                  MessageDecoderFactory.createMessageDecoder(context, request.getTopic());
        }

        while (reader.getNext(key, msgValue)) {
          context.progress();
          mapperContext.getCounter("total", "data-read").increment(msgValue.getLength());
          mapperContext.getCounter("total", "event-count").increment(1);
          byte[] bytes = getBytes(msgValue);

          // check the checksum of message
          Message message = new Message(bytes);
          long checksum = key.getChecksum();
          if (checksum != message.checksum()) {
            throw new ChecksumException(
                "Invalid message checksum "
                    + message.checksum()
                    + ". Expected "
                    + key.getChecksum(),
                key.getOffset());
          }

          long tempTime = System.currentTimeMillis();
          CamusWrapper wrapper;
          try {
            wrapper = getWrappedRecord(key.getTopic(), message);
          } catch (Exception e) {
            mapperContext.write(key, new ExceptionWritable(e));
            continue;
          }

          if (wrapper == null) {
            mapperContext.write(key, new ExceptionWritable(new RuntimeException("null record")));
            continue;
          }

          long timeStamp = wrapper.getTimestamp();
          try {
            key.setTime(timeStamp);
            key.setServer(wrapper.getServer());
            key.setService(wrapper.getService());
          } catch (Exception e) {
            mapperContext.write(key, new ExceptionWritable(e));
            continue;
          }

          if (timeStamp < beginTimeStamp) {
            mapperContext.getCounter("total", "skip-old").increment(1);
          } else if (endTimeStamp == 0) {
            DateTime time = new DateTime(timeStamp);
            statusMsg += " begin read at " + time.toString();
            context.setStatus(statusMsg);
            System.out.println(key.getTopic() + " begin read at " + time.toString());
            endTimeStamp = (time.plusHours(this.maxPullHours)).getMillis();
          } else if (timeStamp > endTimeStamp || System.currentTimeMillis() > maxPullTime) {
            statusMsg += " max read at " + new DateTime(timeStamp).toString();
            context.setStatus(statusMsg);
            System.out.println(
                key.getTopic() + " max read at " + new DateTime(timeStamp).toString());
            mapperContext.getCounter("total", "request-time(ms)").increment(reader.getFetchTime());
            closeReader();
          }

          long secondTime = System.currentTimeMillis();
          value.datum(wrapper.getRecord());
          long decodeTime = ((secondTime - tempTime));

          mapperContext.getCounter("total", "decode-time(ms)").increment(decodeTime);

          if (reader != null) {
            mapperContext.getCounter("total", "request-time(ms)").increment(reader.getFetchTime());
          }
          return true;
        }
        reader = null;
      } catch (Throwable t) {
        Exception e = new Exception(t.getLocalizedMessage(), t);
        e.setStackTrace(t.getStackTrace());
        mapperContext.write(key, new ExceptionWritable(e));
        reader = null;
        continue;
      }
    }
  }
Exemple #20
0
  /**
   * If date is not match, will return next closest match. If date is match, will return this date.
   *
   * @param date - reference DateTime instance - never null;
   * @return DateTime instance, never null. Value obeys logic specified above.
   * @throws NoSuchValueException
   */
  DateTime nextClosestMatch(DateTime date) throws NoSuchValueException {
    List<Integer> year = yearsValueGenerator.generateCandidates(date.getYear(), date.getYear());
    TimeNode days = null;
    int lowestMonth = months.getValues().get(0);
    int lowestHour = hours.getValues().get(0);
    int lowestMinute = minutes.getValues().get(0);
    int lowestSecond = seconds.getValues().get(0);

    NearestValue nearestValue;
    DateTime newDate;
    if (year.isEmpty()) {
      int newYear = yearsValueGenerator.generateNextValue(date.getYear());
      days = generateDays(cronDefinition, new DateTime(newYear, lowestMonth, 1, 0, 0));
      return initDateTime(
          yearsValueGenerator.generateNextValue(date.getYear()),
          lowestMonth,
          days.getValues().get(0),
          lowestHour,
          lowestMinute,
          lowestSecond,
          date.getZone());
    }
    if (!months.getValues().contains(date.getMonthOfYear())) {
      nearestValue = months.getNextValue(date.getMonthOfYear(), 0);
      int nextMonths = nearestValue.getValue();
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(date.getYear(), 1, 1, 0, 0, 0, date.getZone())
                .plusYears(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getMonthOfYear()) {
        date = date.plusYears(1);
      }
      days = generateDays(cronDefinition, new DateTime(date.getYear(), nextMonths, 1, 0, 0));
      return initDateTime(
          date.getYear(),
          nextMonths,
          days.getValues().get(0),
          lowestHour,
          lowestMinute,
          lowestSecond,
          date.getZone());
    }
    days = generateDays(cronDefinition, date);
    if (!days.getValues().contains(date.getDayOfMonth())) {
      nearestValue = days.getNextValue(date.getDayOfMonth(), 0);
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0, 0, date.getZone())
                .plusMonths(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getDayOfMonth()) {
        date = date.plusMonths(1);
      }
      return initDateTime(
          date.getYear(),
          date.getMonthOfYear(),
          nearestValue.getValue(),
          lowestHour,
          lowestMinute,
          lowestSecond,
          date.getZone());
    }
    if (!hours.getValues().contains(date.getHourOfDay())) {
      nearestValue = hours.getNextValue(date.getHourOfDay(), 0);
      int nextHours = nearestValue.getValue();
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(
                    date.getYear(),
                    date.getMonthOfYear(),
                    date.getDayOfMonth(),
                    0,
                    0,
                    0,
                    date.getZone())
                .plusDays(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getHourOfDay()) {
        date = date.plusDays(1);
      }
      return initDateTime(
          date.getYear(),
          date.getMonthOfYear(),
          date.getDayOfMonth(),
          nextHours,
          lowestMinute,
          lowestSecond,
          date.getZone());
    }
    if (!minutes.getValues().contains(date.getMinuteOfHour())) {
      nearestValue = minutes.getNextValue(date.getMinuteOfHour(), 0);
      int nextMinutes = nearestValue.getValue();
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(
                    date.getYear(),
                    date.getMonthOfYear(),
                    date.getDayOfMonth(),
                    date.getHourOfDay(),
                    0,
                    0,
                    date.getZone())
                .plusHours(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getMinuteOfHour()) {
        date = date.plusHours(1);
      }
      return initDateTime(
          date.getYear(),
          date.getMonthOfYear(),
          date.getDayOfMonth(),
          date.getHourOfDay(),
          nextMinutes,
          lowestSecond,
          date.getZone());
    }
    if (!seconds.getValues().contains(date.getSecondOfMinute())) {
      nearestValue = seconds.getNextValue(date.getSecondOfMinute(), 0);
      int nextSeconds = nearestValue.getValue();
      if (nearestValue.getShifts() > 0) {
        newDate =
            new DateTime(
                    date.getYear(),
                    date.getMonthOfYear(),
                    date.getDayOfMonth(),
                    date.getHourOfDay(),
                    date.getMinuteOfHour(),
                    0,
                    date.getZone())
                .plusMinutes(nearestValue.getShifts());
        return nextClosestMatch(newDate);
      }
      if (nearestValue.getValue() < date.getSecondOfMinute()) {
        date = date.plusMinutes(1);
      }
      return initDateTime(
          date.getYear(),
          date.getMonthOfYear(),
          date.getDayOfMonth(),
          date.getHourOfDay(),
          date.getMinuteOfHour(),
          nextSeconds,
          date.getZone());
    }
    return date;
  }
Exemple #21
0
 public static Date plusHours(Date date, int numberOfHours) {
   if (date == null) date = new Date();
   DateTime dt = new DateTime(date);
   return dt.plusHours(numberOfHours).toDate();
 }
Exemple #22
0
 public static String computeTime(String dateString, String val, String timeUnit) {
   DateTime date = new DateTime();
   int value = 0;
   boolean isLong = false;
   if (!Strings.isEmpty(val) && !Strings.isEmpty(dateString) && !Strings.isEmpty(timeUnit)) {
     if (dateString.substring(dateString.indexOf("T") + 1, dateString.length()).length() == 0) {
       dateString = dateString + DEFAULT_TIME_FORMAT;
     }
     date = new DateTime(dateString);
     if (val.indexOf(".") > 0) {
       val = val.substring(0, val.indexOf("."));
     }
     Long l = new Long(val);
     if ((l.longValue() < 0 && -l.longValue() > 32768)
         || (l.longValue() > 0 && l.longValue() > 32768)) {
       isLong = true;
     }
     if (!isLong) {
       value = Integer.parseInt(val);
     }
     if (!Strings.isEmpty(timeUnit)) {
       if (timeUnit.equals("d")) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusDays(value);
           } else {
             date = date.minusDays(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 24 * 60 * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 24 * 60 * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(HOUR)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusHours(value);
           } else {
             date = date.minusHours(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 60 * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 60 * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(MIN)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusMinutes(value);
           } else {
             date = date.minusMinutes(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 60 * 1000);
           } else {
             date = date.plus(l.longValue() * 60 * 1000);
           }
         }
       } else if (timeUnit.equals(SEC)) {
         if (!isLong) {
           if (value > 0) {
             date = date.plusSeconds(value);
           } else {
             date = date.minusSeconds(-value);
           }
         } else {
           if (l.longValue() < 0) {
             date = date.minus(-l.longValue() * 1000);
           } else {
             date = date.plus(l.longValue() * 1000);
           }
         }
       }
     }
   }
   return FormatUtils.formatDateTimeToISO(date.toDate());
 }