org.joda.time.Period Java Examples

The following examples show how to use org.joda.time.Period. 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: TaskDueDateExtensionsTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testRelativeDueDate() {
  Map<String, Object> variables = new HashMap<String, Object>();
  variables.put("dateVariable", "P2DT2H30M");
  
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("dueDateExtension", variables);

  Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
  
  
  Date dueDate = task.getDueDate();
  assertNotNull(dueDate);
  
  Period period = new Period(task.getCreateTime().getTime(), dueDate.getTime());
  assertEquals(period.getDays(), 2);
  assertEquals(period.getHours(), 2);
  assertEquals(period.getMinutes(), 30);
}
 
Example #2
Source File: TestUserProfileUtils.java    From Eagle with Apache License 2.0 6 votes vote down vote up
@Test
 public void testFormatSecondsByPeriod1H() throws ParseException {

    Period period = new Period("PT1h");
    Seconds seconds = period.toStandardSeconds();
    Assert.assertEquals(60*60,seconds.getSeconds());

    long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
    long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:00:00");
    long result = UserProfileUtils.formatSecondsByPeriod(time,seconds);
    Assert.assertEquals(expect,result);

    time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
    expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
    result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
    Assert.assertEquals(expect,result);

    time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:30:59");
    expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
    result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
    Assert.assertEquals(expect,result);
}
 
Example #3
Source File: TimePeriodUtilsTest.java    From eagle with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormatSecondsByPeriod15M() throws ParseException {

    Period period = new Period("PT15m");
    Seconds seconds = period.toStandardSeconds();
    Assert.assertEquals(15 * 60, seconds.getSeconds());

    long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
    long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:45:00");
    long result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
    Assert.assertEquals(expect, result);

    time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
    expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
    result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
    Assert.assertEquals(expect, result);

    time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
    expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
    result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
    Assert.assertEquals(expect, result);
}
 
Example #4
Source File: UIUtils.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * Format the duration in milliseconds to a human readable String, with "yr", "days", "hr" etc prefixes
 *
 *
 * @param durationMs Duration in milliseconds
 * @return Human readable string
 */
public static String formatDuration(long durationMs){
    Period period = Period.seconds((int)(durationMs/1000L));
    Period p2 = period.normalizedStandard(PeriodType.yearMonthDayTime());

    PeriodFormatter formatter = new PeriodFormatterBuilder()
            .appendYears()
            .appendSuffix(" yr ")
            .appendMonths()
            .appendSuffix(" months ")
            .appendDays()
            .appendSuffix(" days ")
            .appendHours()
            .appendSuffix(" hr ")
            .appendMinutes()
            .appendSuffix(" min ")
            .appendSeconds()
            .appendSuffix(" sec")
            .toFormatter();

    return formatter.print(p2);
}
 
Example #5
Source File: DateTimeService.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
public static DateTime getTimeSlice(DateTime dt, Duration duration) {
    Period p = duration.toPeriod();

    if (p.getYears() != 0) {
        return dt.yearOfEra().roundFloorCopy().minusYears(dt.getYearOfEra() % p.getYears());
    } else if (p.getMonths() != 0) {
        return dt.monthOfYear().roundFloorCopy().minusMonths((dt.getMonthOfYear() - 1) % p.getMonths());
    } else if (p.getWeeks() != 0) {
        return dt.weekOfWeekyear().roundFloorCopy().minusWeeks((dt.getWeekOfWeekyear() - 1) % p.getWeeks());
    } else if (p.getDays() != 0) {
        return dt.dayOfMonth().roundFloorCopy().minusDays((dt.getDayOfMonth() - 1) % p.getDays());
    } else if (p.getHours() != 0) {
        return dt.hourOfDay().roundFloorCopy().minusHours(dt.getHourOfDay() % p.getHours());
    } else if (p.getMinutes() != 0) {
        return dt.minuteOfHour().roundFloorCopy().minusMinutes(dt.getMinuteOfHour() % p.getMinutes());
    } else if (p.getSeconds() != 0) {
        return dt.secondOfMinute().roundFloorCopy().minusSeconds(dt.getSecondOfMinute() % p.getSeconds());
    }
    return dt.millisOfSecond().roundCeilingCopy().minusMillis(dt.getMillisOfSecond() % p.getMillis());
}
 
Example #6
Source File: TestISOPeriodFormat.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testFormatStandard_negative() {
    Period p = new Period(-1, -2, -3, -4, -5, -6, -7, -8);
    assertEquals("P-1Y-2M-3W-4DT-5H-6M-7.008S", ISOPeriodFormat.standard().print(p));
    
    p = Period.years(-54);
    assertEquals("P-54Y", ISOPeriodFormat.standard().print(p));
    
    p = Period.seconds(4).withMillis(-8);
    assertEquals("PT3.992S", ISOPeriodFormat.standard().print(p));
    
    p = Period.seconds(-4).withMillis(8);
    assertEquals("PT-3.992S", ISOPeriodFormat.standard().print(p));
    
    p = Period.seconds(-23);
    assertEquals("PT-23S", ISOPeriodFormat.standard().print(p));
    
    p = Period.millis(-8);
    assertEquals("PT-0.008S", ISOPeriodFormat.standard().print(p));
}
 
Example #7
Source File: PeriodParserTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testPredefinedPeriods() {
    Period period;

    period = Job.PERIOD_FORMATTER.parsePeriod(Every.DAY);
    Assertions.assertThat(period.getDays()).isEqualTo(1);
    Assertions.assertThat(period.getHours()).isEqualTo(0);
    Assertions.assertThat(period.getMinutes()).isEqualTo(0);

    period = Job.PERIOD_FORMATTER.parsePeriod(Every.HOUR);
    Assertions.assertThat(period.getDays()).isEqualTo(0);
    Assertions.assertThat(period.getHours()).isEqualTo(1);
    Assertions.assertThat(period.getMinutes()).isEqualTo(0);

    period = Job.PERIOD_FORMATTER.parsePeriod(Every.MINUTE);
    Assertions.assertThat(period.getDays()).isEqualTo(0);
    Assertions.assertThat(period.getHours()).isEqualTo(0);
    Assertions.assertThat(period.getMinutes()).isEqualTo(1);
}
 
Example #8
Source File: TestBasics.java    From activitystreams with Apache License 2.0 6 votes vote down vote up
@Test
public void testDateTimes() {
  DateTime now = DateTime.now();
  ASObject obj = 
    Makers.object()
      .updated(now)
      .published(now)
      .startTime(now.minus(Period.days(1)))
      .endTime(now.plus(Period.days(1)))
      .get();
  assertNotNull(obj.updated());
  assertNotNull(obj.published());
  assertNotNull(obj.startTime());
  assertNotNull(obj.endTime());
  assertEquals(now, obj.updated());
  assertEquals(now, obj.published());
  assertTrue(now.isAfter(obj.startTime()));
  assertTrue(now.isBefore(obj.endTime()));
}
 
Example #9
Source File: OngoingNotificationsReceiver.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
private Bitmap getIconFromMinutes(Times t) {
    int left = new Period(LocalDateTime.now(), t.getTime(LocalDate.now(), t.getNextTime()), PeriodType.minutes()).getMinutes();
    Resources r = getContext().getResources();

    int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, r.getDisplayMetrics());
    Bitmap b = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(0xFFFFFFFF);
    paint.setTextAlign(Paint.Align.CENTER);
    paint.setTextSize(size);
    paint.setTextSize(size * size / paint.measureText((left < 10 ? left * 10 : left) + ""));
    float yPos = c.getHeight() / 2f - (paint.descent() + paint.ascent()) / 2;
    c.drawText(left + "", size / 2f, yPos, paint);
    return b;
}
 
Example #10
Source File: EwsUtilities.java    From ews-java-api with MIT License 6 votes vote down vote up
/**
 * Takes an xs:duration string as defined by the W3 Consortiums
 * Recommendation "XML Schema Part 2: Datatypes Second Edition",
 * http://www.w3.org/TR/xmlschema-2/#duration, and converts it into a
 * System.TimeSpan structure This method uses the following approximations:
 * 1 year = 365 days 1 month = 30 days Additionally, it only allows for four
 * decimal points of seconds precision.
 *
 * @param xsDuration xs:duration string to convert
 * @return System.TimeSpan structure
 */
public static TimeSpan getXSDurationToTimeSpan(String xsDuration) {
  // TODO: Need to check whether this should be the equivalent or not
  Matcher m = PATTERN_TIME_SPAN.matcher(xsDuration);
  boolean negative = false;
  if (m.find()) {
    negative = true;
  }

  // Removing leading '-'
  if (negative) {
    xsDuration = xsDuration.replace("-P", "P");
  }

  Period period = Period.parse(xsDuration, ISOPeriodFormat.standard());
    
  long retval = period.toStandardDuration().getMillis();
  
  if (negative) {
    retval = -retval;
  }

  return new TimeSpan(retval);

}
 
Example #11
Source File: DruidTranquilityController.java    From nifi with Apache License 2.0 6 votes vote down vote up
Beam<Map<String, Object>> buildBeam(String dataSource, String indexService, String discoveryPath, int clusterPartitions, int clusterReplication,
                                    String segmentGranularity, String queryGranularity, String windowPeriod, String firehoseGracePeriod, String indexRetryPeriod, DruidDimensions dimensions,
                                    List<AggregatorFactory> aggregator, Timestamper<Map<String, Object>> timestamper, TimestampSpec timestampSpec) {
    return DruidBeams.builder(timestamper)
            .curator(curator)
            .discoveryPath(discoveryPath)
            .location(DruidLocation.create(DruidEnvironment.create(indexService, FIREHOSE_PATTERN), dataSource))
            .timestampSpec(timestampSpec)
            .rollup(DruidRollup.create(dimensions, aggregator, QueryGranularity.fromString(queryGranularity)))
            .tuning(
                    ClusteredBeamTuning
                            .builder()
                            .segmentGranularity(getGranularity(segmentGranularity))
                            .windowPeriod(new Period(windowPeriod))
                            .partitions(clusterPartitions)
                            .replicants(clusterReplication)
                            .build()
            )
            .druidBeamConfig(
                    DruidBeamConfig
                            .builder()
                            .indexRetryPeriod(new Period(indexRetryPeriod))
                            .firehoseGracePeriod(new Period(firehoseGracePeriod))
                            .build())
            .buildBeam();
}
 
Example #12
Source File: LiteralValueFormatter.java    From crate with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void formatValue(Object value, StringBuilder builder) {
    if (value == null) {
        builder.append("NULL");
    } else if (value instanceof Map) {
        formatMap((Map<String, Object>) value, builder);
    } else if (value instanceof Collection) {
        formatIterable((Iterable<?>) value, builder);
    } else if (value.getClass().isArray()) {
        formatArray(value, builder);
    } else if (value instanceof String || value instanceof Point || value instanceof Period) {
        builder.append(Literals.quoteStringLiteral(value.toString()));
    } else if (value instanceof Long
               && ((Long) value <= Integer.MAX_VALUE
               || (Long) value >= Integer.MIN_VALUE)) {
        builder.append(value.toString());
        builder.append("::bigint");
    } else {
        builder.append(value.toString());
    }
}
 
Example #13
Source File: TimePeriodUtilsTest.java    From eagle with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormatSecondsByPeriod1H() throws ParseException {

    Period period = new Period("PT1h");
    Seconds seconds = period.toStandardSeconds();
    Assert.assertEquals(60 * 60, seconds.getSeconds());

    long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
    long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:00:00");
    long result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
    Assert.assertEquals(expect, result);

    time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
    expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
    result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
    Assert.assertEquals(expect, result);

    time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:30:59");
    expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
    result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
    Assert.assertEquals(expect, result);
}
 
Example #14
Source File: NoDataPolicyHandler.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare(Collector<AlertStreamEvent> collector, PolicyHandlerContext context) throws Exception {
    this.collector = collector;
    this.context = context;
    this.policyDef = context.getPolicyDefinition();
    List<String> inputStreams = policyDef.getInputStreams();
    // validate inputStreams has to contain only one stream
    if (inputStreams.size() != 1) {
        throw new IllegalArgumentException("policy inputStream size has to be 1 for no data alert");
    }
    // validate outputStream has to contain only one stream
    if (policyDef.getOutputStreams().size() != 1) {
        throw new IllegalArgumentException("policy outputStream size has to be 1 for no data alert");
    }

    String is = inputStreams.get(0);
    StreamDefinition sd = sds.get(is);

    String policyValue = policyDef.getDefinition().getValue();
    // assume that no data alert policy value consists of "windowPeriod, type, numOfFields, f1_name, f2_name, f1_value, f2_value, f1_value, f2_value}
    String[] segments = policyValue.split(",");
    long windowPeriod = TimePeriodUtils.getMillisecondsOfPeriod(Period.parse(segments[0]));
    distinctWindow = new DistinctValuesInTimeWindow(windowPeriod);
    this.wisbType = NoDataWisbType.valueOf(segments[1]);
    // for provided wisb values, need to parse, for dynamic wisb values, it is computed through a window
    if (wisbType == NoDataWisbType.provided) {
        wisbValues = new NoDataWisbProvidedParser().parse(segments);
    }
    // populate wisb field names
    int numOfFields = Integer.parseInt(segments[2]);
    for (int i = 3; i < 3 + numOfFields; i++) {
        String fn = segments[i];
        wisbFieldIndices.add(sd.getColumnIndex(fn));
    }
}
 
Example #15
Source File: TestMetadataSpecSerDeser.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Test
public void testRouterBoltSpec() {
    List<String> topics = Arrays.asList("testTopic3", "testTopic4", "testTopic5");
    RouterSpec boltSpec = new RouterSpec();
    for (String topic : topics) {
        String streamId = getStreamNameByTopic(topic);
        // StreamPartition, groupby col1 for stream cpuUsageStream
        StreamPartition sp = new StreamPartition();
        sp.setStreamId(streamId);
        sp.setColumns(Arrays.asList("value"));
        sp.setType(StreamPartition.Type.GROUPBY);

        StreamSortSpec sortSpec = new StreamSortSpec();
        sortSpec.setWindowMargin(1000);
        sortSpec.setWindowPeriod2(Period.seconds(10));
        sp.setSortSpec(sortSpec);

        // set StreamRouterSpec to have 2 WorkSlot
        StreamRouterSpec routerSpec = new StreamRouterSpec();
        routerSpec.setPartition(sp);
        routerSpec.setStreamId(streamId);
        PolicyWorkerQueue queue = new PolicyWorkerQueue();
        queue.setPartition(sp);
        queue.setWorkers(Arrays.asList(new WorkSlot("testTopology", "alertBolt0"), new WorkSlot("testTopology", "alertBolt1")));
        routerSpec.setTargetQueue(Arrays.asList(queue));
        boltSpec.addRouterSpec(routerSpec);
    }

    String json = MetadataSerDeser.serialize(boltSpec);
    System.out.println(json);
    RouterSpec deserializedSpec = MetadataSerDeser.deserialize(json, RouterSpec.class);
    Assert.assertEquals(3, deserializedSpec.getRouterSpecs().size());
}
 
Example #16
Source File: TestPeriodFormatterBuilder.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testFormatPrefixPlural2() {
    PeriodFormatter f = builder.appendPrefix("Hour:", "Hours:").appendHours().toFormatter();
    assertEquals("Hours:5", f.print(PERIOD));
    assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
    
    Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
    assertEquals("Hours:0", f.print(p));
    assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
 
Example #17
Source File: ExtendedJsonOutput.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void writeInterval(Period value) throws IOException {
  gen.writeStartObject();
  gen.writeFieldName(ExtendedType.INTERVAL.serialized);
  super.writeInterval(value);
  gen.writeEndObject();
}
 
Example #18
Source File: RedisCacheImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Period maintenanceWindow) {
    return this.withPatchSchedule(new ScheduleEntry()
            .withDayOfWeek(dayOfWeek)
            .withStartHourUtc(startHourUtc)
            .withMaintenanceWindow(maintenanceWindow));
}
 
Example #19
Source File: DruidSqlCastConverter.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static String castCharToDateTime(
    TimeZone timeZone,
    String operand,
    final SqlTypeName toType, String format) {
  // Cast strings to date times by parsing them from SQL format.
  final String timestampExpression = DruidExpressions.functionCall(
      "timestamp_parse",
      ImmutableList.of(
          operand,
          DruidExpressions.stringLiteral(format),
          DruidExpressions.stringLiteral(timeZone.getID())));

  if (toType == SqlTypeName.DATE) {
    // case to date we need to floor to day first
    return DruidExpressions.applyTimestampFloor(
        timestampExpression,
        Period.days(1).toString(),
        "",
        timeZone);
  } else if (toType == SqlTypeName.TIMESTAMP
      || toType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) {
    return timestampExpression;
  } else {
    throw new IllegalStateException(
        DruidQuery.format("Unsupported DateTime type[%s]", toType));
  }
}
 
Example #20
Source File: Output.java    From helios with Apache License 2.0 5 votes vote down vote up
public static String humanDuration(final Duration dur) {
  final Period p = dur.toPeriod().normalizedStandard();

  if (dur.getStandardSeconds() == 0) {
    return "0 seconds";
  } else if (dur.getStandardSeconds() < 60) {
    return format("%d second%s", p.getSeconds(), p.getSeconds() > 1 ? "s" : "");
  } else if (dur.getStandardMinutes() < 60) {
    return format("%d minute%s", p.getMinutes(), p.getMinutes() > 1 ? "s" : "");
  } else if (dur.getStandardHours() < 24) {
    return format("%d hour%s", p.getHours(), p.getHours() > 1 ? "s" : "");
  } else {
    return format("%d day%s", dur.getStandardDays(), dur.getStandardDays() > 1 ? "s" : "");
  }
}
 
Example #21
Source File: DateUtilities.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static Period fromIntervalYear(int value) {
  final int years  = (value / yearsToMonths);
  final int months = (value % yearsToMonths);
  return new Period()
      .plusYears(years)
      .plusMonths(months);
}
 
Example #22
Source File: AddDuration.java    From spork with Apache License 2.0 5 votes vote down vote up
@Override
public DateTime exec(Tuple input) throws IOException {
    if (input == null || input.size() < 2 || input.get(0) == null || input.get(1) == null) {
        return null;
    }
    
    return ((DateTime) input.get(0)).plus(new Period((String) input.get(1)));
}
 
Example #23
Source File: IntervalAnalysisTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void test_seconds_millis() throws Exception {
    var symbol =  e.asSymbol("INTERVAL '1'");
    assertThat(symbol, isLiteral(new Period().withSeconds(1)));

    symbol =  e.asSymbol("INTERVAL '1.1'");
    assertThat(symbol, isLiteral(new Period().withSeconds(1).withMillis(100)));

    symbol =  e.asSymbol("INTERVAL '60.1'");
    assertThat(symbol, isLiteral(new Period().withMinutes(1).withMillis(100)));
}
 
Example #24
Source File: PGTypesTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void test_period_text_round_trip_streaming() {
    Entry entry = new Entry(DataTypes.INTERVAL, new Period(1, 2, 3, 4, 5, 6, 7, 8));
    assertThat(
        writeAndReadAsText(entry, IntervalType.INSTANCE),
        is(entry.value)
    );
}
 
Example #25
Source File: TestPeriodFormatterBuilder.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testFormatPrefixPlural1() {
    PeriodFormatter f = builder.appendPrefix("Year:", "Years:").appendYears().toFormatter();
    assertEquals("Year:1", f.print(PERIOD));
    assertEquals(6, f.getPrinter().calculatePrintedLength(PERIOD, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
    
    Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
    assertEquals("Years:0", f.print(p));
    assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
    assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
 
Example #26
Source File: WebAppConfiguration.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
private Duration parseDuration(String initParameter, Duration defaultDuration)
{
	if (initParameter!=null)
	{
		PeriodFormatter formatter = new PeriodFormatterBuilder()
    		.appendDays().appendSuffix("d ")
    		.appendHours().appendSuffix("h ")
    		.appendMinutes().appendSuffix("min")
    		.toFormatter();
		Period p = formatter.parsePeriod(initParameter);
		return p.toDurationFrom(DateTime.now());
	} else
		return defaultDuration;
}
 
Example #27
Source File: Utils.java    From dungeon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given a duration in milliseconds, this method returns a human-readable period string.
 *
 * @param duration a duration in milliseconds, nonnegative
 * @return a String
 */
public static String makePeriodString(long duration) {
  if (duration < 0) {
    throw new IllegalArgumentException("duration should be nonnegative.");
  }
  Period period = new Period(duration).normalizedStandard();
  period = withMostSignificantNonZeroFieldsOnly(period, 1);
  return PeriodFormat.wordBased(Locale.ENGLISH).print(period);
}
 
Example #28
Source File: SettingsDataSource.java    From BrainPhaser with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Applies default values to a settings object
 * @param settings object to reset to defaults
 */
public void setToDefaultSettings(Settings settings) {
    settings.setTimeBoxStage1(new Date(Period.minutes(5).toStandardDuration().getMillis()));
    settings.setTimeBoxStage2(new Date(Period.hours(1).toStandardDuration().getMillis()));
    settings.setTimeBoxStage3(new Date(Period.days(1).toStandardDuration().getMillis()));
    settings.setTimeBoxStage4(new Date(Period.weeks(1).toStandardDuration().getMillis()));
    settings.setTimeBoxStage5(new Date(Period.weeks(4).toStandardDuration().getMillis())); // a Month
    settings.setTimeBoxStage6(new Date(Period.weeks(24).toStandardDuration().getMillis())); // 6 Months
}
 
Example #29
Source File: EstatioFakeDataService.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Programmatic
public LocalDate around(final Period period) {
    final LocalDate now = clockService.now();
    return randomService.nextDouble() < 0.5 ? before(period): after(period);
}
 
Example #30
Source File: Formatter.java    From cukedoctor with Apache License 2.0 4 votes vote down vote up
public static String formatTime(Long time) {
	return TIME_FORMATTER.print(new Period(0, time / 1000000));
}