org.joda.time.PeriodType Java Examples

The following examples show how to use org.joda.time.PeriodType. 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: 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 #2
Source File: PeriodFormatterBuilder.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
boolean isSupported(PeriodType type, int field) {
    switch (field) {
    default:
        return false;
    case YEARS:
        return type.isSupported(DurationFieldType.years());
    case MONTHS:
        return type.isSupported(DurationFieldType.months());
    case WEEKS:
        return type.isSupported(DurationFieldType.weeks());
    case DAYS:
        return type.isSupported(DurationFieldType.days());
    case HOURS:
        return type.isSupported(DurationFieldType.hours());
    case MINUTES:
        return type.isSupported(DurationFieldType.minutes());
    case SECONDS:
        return type.isSupported(DurationFieldType.seconds());
    case MILLIS:
        return type.isSupported(DurationFieldType.millis());
    case SECONDS_MILLIS: // drop through
    case SECONDS_OPTIONAL_MILLIS:
        return type.isSupported(DurationFieldType.seconds()) ||
               type.isSupported(DurationFieldType.millis());
    }
}
 
Example #3
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 #4
Source File: ConfigUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Helper for parsing a period string from config (e.g. '3 days', '1min', '3600000')
 *
 * @param period
 * @return
 */
public static Period parsePeriod(String period) {
  Matcher m = PATTERN_PERIOD.matcher(period);
  if (!m.find()) {
    throw new IllegalArgumentException(String.format("Could not parse period expression '%s'", period));
  }

  int size = Integer.valueOf(m.group(1).trim());

  PeriodType t = PeriodType.millis();
  if (m.group(2).length() > 0) {
    t = parsePeriodType(m.group(2).trim());
  }

  return new Period().withFieldAdded(t.getFieldType(0), size);
}
 
Example #5
Source File: Times.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
public boolean isKerahat() {
    LocalDateTime now = LocalDateTime.now();

    int untilSun = new Period(getTime(now.toLocalDate(), Vakit.SUN.ordinal()), now, PeriodType.minutes()).getMinutes();
    if (untilSun >= 0 && untilSun < Preferences.KERAHAT_SUNRISE.get()) {
        return true;
    }

    int untilDhuhr = new Period(now, getTime(now.toLocalDate(), Vakit.DHUHR.ordinal()), PeriodType.minutes()).getMinutes();
    if ((untilDhuhr >= 0) && (untilDhuhr < (Preferences.KERAHAT_ISTIWA.get()))) {
        return true;
    }

    int untilMaghrib = new Period(now, getTime(now.toLocalDate(), Vakit.MAGHRIB.ordinal()), PeriodType.minutes()).getMinutes();
    return (untilMaghrib >= 0) && (untilMaghrib < (Preferences.KERAHAT_SUNSET.get()));
}
 
Example #6
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 #7
Source File: BreakOption.java    From estatio with Apache License 2.0 6 votes vote down vote up
@MemberOrder(name = "breakDate", sequence = "1")
public BreakOption changeDates(
        final LocalDate breakDate,
        final LocalDate excerciseDate) {
    setBreakDate(breakDate);
    setExerciseDate(excerciseDate);
    LocalDateInterval ldi = new LocalDateInterval(excerciseDate, breakDate, AbstractInterval.IntervalEnding.EXCLUDING_END_DATE);
    final String s = JodaPeriodUtils.asSimpleString(new Period(ldi.asInterval(), PeriodType.yearMonthDay()));
    setNotificationPeriod(s);

    // re-create events
    removeExistingEvents();
    createEvents();

    return this;
}
 
Example #8
Source File: Time_27_PeriodFormatterBuilder_s.java    From coming with MIT License 6 votes vote down vote up
boolean isSupported(PeriodType type, int field) {
    switch (field) {
    default:
        return false;
    case YEARS:
        return type.isSupported(DurationFieldType.years());
    case MONTHS:
        return type.isSupported(DurationFieldType.months());
    case WEEKS:
        return type.isSupported(DurationFieldType.weeks());
    case DAYS:
        return type.isSupported(DurationFieldType.days());
    case HOURS:
        return type.isSupported(DurationFieldType.hours());
    case MINUTES:
        return type.isSupported(DurationFieldType.minutes());
    case SECONDS:
        return type.isSupported(DurationFieldType.seconds());
    case MILLIS:
        return type.isSupported(DurationFieldType.millis());
    case SECONDS_MILLIS: // drop through
    case SECONDS_OPTIONAL_MILLIS:
        return type.isSupported(DurationFieldType.seconds()) ||
               type.isSupported(DurationFieldType.millis());
    }
}
 
Example #9
Source File: BaselineTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Test
public void testBaselineAggregateComputeMultiIndex() {
  BaselineAggregate baseline = BaselineAggregate.fromOffsets(BaselineAggregateType.MEDIAN, makePeriods(PeriodType.millis(), -1200L, -4500L), DateTimeZone.UTC);

  Map<MetricSlice, DataFrame> data = new HashMap<>();
  data.put(BASE_SLICE.withStart(13800).withEnd(15800),
      new DataFrame()
          .addSeries(COL_TIME, LongSeries.buildFrom(13800L, 13800L, 14300L, 14300L, 14800L, 14800L, 15300L, 15300L))
          .addSeries("string", StringSeries.buildFrom("A", "B", "A", "B", "A", "B", "A", "B"))
          .addSeries(COL_VALUE, 400d, 4000d, 500d, 5000d, 600d, 6000d, 700d, 7000d)
          .setIndex(COL_TIME, "string")
  );
  data.put(BASE_SLICE.withStart(10500).withEnd(12500),
      new DataFrame()
          .addSeries(COL_TIME, LongSeries.buildFrom(10500L, 11000L, 11500L, 12000L, 10500, 11000L, 11500L, 12000L))
          .addSeries("string", StringSeries.buildFrom("A", "A", "A", "A", "B", "B", "B", "B"))
          .addSeries(COL_VALUE, 500d, 600d, 700d, 800d, 5000d, 6000d, 7000d, 8000d)
          .setIndex(COL_TIME, "string")
  );

  DataFrame result = baseline.gather(BASE_SLICE, data).sortedBy("string", COL_TIME);

  assertEquals(result.getLongs(COL_TIME), 15000L, 15500L, 16000L, 16500L, 15000L, 15500L, 16000L, 16500L);
  assertEquals(result.getStrings("string"), "A", "A", "A", "A", "B", "B", "B", "B");
  assertEquals(result.getDoubles(COL_VALUE), 450d, 550d, 650d, 750d, 4500d, 5500d, 6500d, 7500d);
}
 
Example #10
Source File: Time_27_PeriodFormatterBuilder_t.java    From coming with MIT License 6 votes vote down vote up
boolean isSupported(PeriodType type, int field) {
    switch (field) {
    default:
        return false;
    case YEARS:
        return type.isSupported(DurationFieldType.years());
    case MONTHS:
        return type.isSupported(DurationFieldType.months());
    case WEEKS:
        return type.isSupported(DurationFieldType.weeks());
    case DAYS:
        return type.isSupported(DurationFieldType.days());
    case HOURS:
        return type.isSupported(DurationFieldType.hours());
    case MINUTES:
        return type.isSupported(DurationFieldType.minutes());
    case SECONDS:
        return type.isSupported(DurationFieldType.seconds());
    case MILLIS:
        return type.isSupported(DurationFieldType.millis());
    case SECONDS_MILLIS: // drop through
    case SECONDS_OPTIONAL_MILLIS:
        return type.isSupported(DurationFieldType.seconds()) ||
               type.isSupported(DurationFieldType.millis());
    }
}
 
Example #11
Source File: Time_13_PeriodFormatterBuilder_s.java    From coming with MIT License 6 votes vote down vote up
boolean isSupported(PeriodType type, int field) {
    switch (field) {
    default:
        return false;
    case YEARS:
        return type.isSupported(DurationFieldType.years());
    case MONTHS:
        return type.isSupported(DurationFieldType.months());
    case WEEKS:
        return type.isSupported(DurationFieldType.weeks());
    case DAYS:
        return type.isSupported(DurationFieldType.days());
    case HOURS:
        return type.isSupported(DurationFieldType.hours());
    case MINUTES:
        return type.isSupported(DurationFieldType.minutes());
    case SECONDS:
        return type.isSupported(DurationFieldType.seconds());
    case MILLIS:
        return type.isSupported(DurationFieldType.millis());
    case SECONDS_MILLIS: // drop through
    case SECONDS_OPTIONAL_MILLIS:
        return type.isSupported(DurationFieldType.seconds()) ||
               type.isSupported(DurationFieldType.millis());
    }
}
 
Example #12
Source File: StringColumnPeriodMapper.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
  public String toNonNullValue(Period value) {
  	
  	final String periodString; 
if (STANDARD.equals(value.getPeriodType())) {
	periodString = value.toString();
} else {
	if (PeriodType.class.equals(value.getPeriodType().getClass())) {
		periodString = value.toString() + "{" + value.getPeriodType().getName() + "}";
	} else {
		
		throw new IllegalArgumentException("Subclasses of PeriodType are unsupported");
	}
}
return periodString;
  }
 
Example #13
Source File: PeriodFormatterBuilder.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
boolean isSupported(PeriodType type, int field) {
    switch (field) {
    default:
        return false;
    case YEARS:
        return type.isSupported(DurationFieldType.years());
    case MONTHS:
        return type.isSupported(DurationFieldType.months());
    case WEEKS:
        return type.isSupported(DurationFieldType.weeks());
    case DAYS:
        return type.isSupported(DurationFieldType.days());
    case HOURS:
        return type.isSupported(DurationFieldType.hours());
    case MINUTES:
        return type.isSupported(DurationFieldType.minutes());
    case SECONDS:
        return type.isSupported(DurationFieldType.seconds());
    case MILLIS:
        return type.isSupported(DurationFieldType.millis());
    case SECONDS_MILLIS: // drop through
    case SECONDS_OPTIONAL_MILLIS:
        return type.isSupported(DurationFieldType.seconds()) ||
               type.isSupported(DurationFieldType.millis());
    }
}
 
Example #14
Source File: BaselineTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private static List<Period> makePeriods(PeriodType periodType, long... offsetMillis) {
  List<Period> output = new ArrayList<>();
  for (long offset : offsetMillis) {
    output.add(new Period(offset, periodType));
  }
  return output;
}
 
Example #15
Source File: Main.java    From spork with Apache License 2.0 5 votes vote down vote up
private static void printScriptRunTime(DateTime startTime) {
    DateTime endTime = new DateTime();
    Duration duration = new Duration(startTime, endTime);
    Period period = duration.toPeriod().normalizedStandard(PeriodType.time());
    log.info("Pig script completed in "
            + PeriodFormat.getDefault().print(period)
            + " (" + duration.getMillis() + " ms)");
}
 
Example #16
Source File: MockThirdEyeDataSource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a DataFrame populated with mock data for a given config and time range.
 *
 * @param config metric generator config
 * @param start start time
 * @param end end time
 * @param interval time granularity
 * @return DataFrame with mock data
 */
private static DataFrame makeData(Map<String, Object> config, DateTime start, DateTime end, Period interval) {
  List<Long> timestamps = new ArrayList<>();
  List<Double> values = new ArrayList<>();

  double mean = MapUtils.getDoubleValue(config, "mean", 0);
  double std = MapUtils.getDoubleValue(config, "std", 1);
  double daily = MapUtils.getDoubleValue(config, "daily", mean);
  double weekly = MapUtils.getDoubleValue(config, "weekly", daily);
  NormalDistribution dist = new NormalDistribution(mean, std);

  DateTime origin = start.withFields(DataFrameUtils.makeOrigin(PeriodType.days()));
  while (origin.isBefore(end)) {
    if (origin.isBefore(start)) {
      origin = origin.plus(interval);
      continue;
    }

    timestamps.add(origin.getMillis());

    double compDaily = weekly * (COMPONENT_ALPHA_WEEKLY + Math.sin(origin.getDayOfWeek() / 7.0 * 2 * Math.PI + 1) / 2 * (1 - COMPONENT_ALPHA_WEEKLY));
    double compHourly = daily * (COMPONENT_ALPHA_DAILY + Math.sin(origin.getHourOfDay() / 24.0 * 2 * Math.PI + 1) / 2 * (1 - COMPONENT_ALPHA_DAILY));
    double compEpsilon = dist.sample();

    values.add((double) Math.max(Math.round(compDaily + compHourly + compEpsilon), 0));
    origin = origin.plus(interval);
  }

  return new DataFrame()
      .addSeries(COL_TIME, ArrayUtils.toPrimitive(timestamps.toArray(new Long[0])))
      .addSeries(COL_VALUE, ArrayUtils.toPrimitive(values.toArray(new Double[0])))
      .setIndex(COL_TIME);
}
 
Example #17
Source File: Time_22_BasePeriod_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Creates a new period based on another using the {@link ConverterManager}.
 *
 * @param period  the period to convert
 * @param type  which set of fields this period supports, null means use type from object
 * @param chrono  the chronology to use, null means ISO default
 * @throws IllegalArgumentException if period is invalid
 * @throws IllegalArgumentException if an unsupported field's value is non-zero
 */
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
    super();
    PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
    type = (type == null ? converter.getPeriodType(period) : type);
    type = checkPeriodType(type);
    iType = type;
    if (this instanceof ReadWritablePeriod) {
        iValues = new int[size()];
        chrono = DateTimeUtils.getChronology(chrono);
        converter.setInto((ReadWritablePeriod) this, period, chrono);
    } else {
        iValues = new MutablePeriod(period, type, chrono).getValues();
    }
}
 
Example #18
Source File: DurationRenderer.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private DurationFieldType[] getDurationFieldTypes() {
    List<DurationFieldType> result = new ArrayList<DurationFieldType>();
    if (getIncludedFields() == null) {
        result.add(DurationFieldType.hours());
        result.add(DurationFieldType.minutes());
    } else {
        PeriodType standard = PeriodType.standard();
        for (int index = 0; index < standard.size(); index++) {
            if (getIncludedFields().contains(standard.getFieldType(index).getName())) {
                result.add(standard.getFieldType(index));
            }
        }
    }
    return result.toArray(new DurationFieldType[] {});
}
 
Example #19
Source File: TestStringConverter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testSetIntoPeriod_Object3() throws Exception {
    MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime());
    StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M48.034S", null);
    assertEquals(2, m.getYears());
    assertEquals(4, m.getWeeks());
    assertEquals(3, m.getDays());
    assertEquals(12, m.getHours());
    assertEquals(24, m.getMinutes());
    assertEquals(48, m.getSeconds());
    assertEquals(34, m.getMillis());
}
 
Example #20
Source File: TestPeriodFormatter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testWithGetParseTypeMethods() {
    PeriodFormatter f2 = f.withParseType(PeriodType.dayTime());
    assertEquals(PeriodType.dayTime(), f2.getParseType());
    assertSame(f2, f2.withParseType(PeriodType.dayTime()));
    
    f2 = f.withParseType(null);
    assertEquals(null, f2.getParseType());
    assertSame(f2, f2.withParseType(null));
}
 
Example #21
Source File: TestStringConverter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testSetIntoPeriod_Object3() throws Exception {
    MutablePeriod m = new MutablePeriod(PeriodType.yearWeekDayTime());
    StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M48.034S", null);
    assertEquals(2, m.getYears());
    assertEquals(4, m.getWeeks());
    assertEquals(3, m.getDays());
    assertEquals(12, m.getHours());
    assertEquals(24, m.getMinutes());
    assertEquals(48, m.getSeconds());
    assertEquals(34, m.getMillis());
}
 
Example #22
Source File: BasePeriod.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a period from the given interval endpoints.
 *
 * @param startInstant  interval start, null means now
 * @param endInstant  interval end, null means now
 * @param type  which set of fields this period supports, null means standard
 * @throws IllegalArgumentException if period type is invalid
 */
protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) {
    super();
    type = checkPeriodType(type);
    if (startInstant == null && endInstant == null) {
        iType = type;
        iValues = new int[size()];
    } else {
        long startMillis = DateTimeUtils.getInstantMillis(startInstant);
        long endMillis = DateTimeUtils.getInstantMillis(endInstant);
        Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant);
        iType = type;
        iValues = chrono.get(this, startMillis, endMillis);
    }
}
 
Example #23
Source File: PeriodFormatter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param printer  the internal printer, null if cannot print
 * @param parser  the internal parser, null if cannot parse
 * @param locale  the locale to use
 * @param type  the parse period type
 */
private PeriodFormatter(
        PeriodPrinter printer, PeriodParser parser,
        Locale locale, PeriodType type) {
    super();
    iPrinter = printer;
    iParser = parser;
    iLocale = locale;
    iParseType = type;
}
 
Example #24
Source File: TestReadableDurationConverter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testSetInto_Object() throws Exception {
    MutablePeriod m = new MutablePeriod(PeriodType.yearMonthDayTime());
    ReadableDurationConverter.INSTANCE.setInto(m, new Duration(
        3L * DateTimeConstants.MILLIS_PER_DAY +
        4L * DateTimeConstants.MILLIS_PER_MINUTE + 5L
    ), null);
    assertEquals(0, m.getYears());
    assertEquals(0, m.getMonths());
    assertEquals(0, m.getWeeks());
    assertEquals(0, m.getDays());
    assertEquals(3 * 24, m.getHours());
    assertEquals(4, m.getMinutes());
    assertEquals(0, m.getSeconds());
    assertEquals(5, m.getMillis());
}
 
Example #25
Source File: BasePeriod.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new period based on another using the {@link ConverterManager}.
 *
 * @param period  the period to convert
 * @param type  which set of fields this period supports, null means use type from object
 * @param chrono  the chronology to use, null means ISO default
 * @throws IllegalArgumentException if period is invalid
 * @throws IllegalArgumentException if an unsupported field's value is non-zero
 */
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
    super();
    PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
    type = (type == null ? converter.getPeriodType(period) : type);
    type = checkPeriodType(type);
    iType = type;
    if (this instanceof ReadWritablePeriod) {
        iValues = new int[size()];
        chrono = DateTimeUtils.getChronology(chrono);
        converter.setInto((ReadWritablePeriod) this, period, chrono);
    } else {
        iValues = new MutablePeriod(period, type, chrono).getValues();
    }
}
 
Example #26
Source File: BaselineTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Test
public void testBaselineAggregateFrom() {
  BaselineAggregate baseline = BaselineAggregate.fromOffsets(BaselineAggregateType.MEDIAN, makePeriods(PeriodType.millis(), -1200L, -4500L), DateTimeZone.UTC);

  List<MetricSlice> slices = baseline.scatter(BASE_SLICE);
  Assert.assertEquals(slices.size(), 2);
  Assert.assertEquals(slices.get(0).getMetricId(), 12345);
  Assert.assertEquals(slices.get(0).getStart(), 13800);
  Assert.assertEquals(slices.get(0).getEnd(), 15800);
  Assert.assertEquals(slices.get(1).getMetricId(), 12345);
  Assert.assertEquals(slices.get(1).getStart(), 10500);
  Assert.assertEquals(slices.get(1).getEnd(), 12500);
}
 
Example #27
Source File: Time_22_BasePeriod_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Creates a period from the given start point and duration.
 *
 * @param startInstant  the interval start, null means now
 * @param duration  the duration of the interval, null means zero-length
 * @param type  which set of fields this period supports, null means standard
 */
protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) {
    super();
    type = checkPeriodType(type);
    long startMillis = DateTimeUtils.getInstantMillis(startInstant);
    long durationMillis = DateTimeUtils.getDurationMillis(duration);
    long endMillis = FieldUtils.safeAdd(startMillis, durationMillis);
    Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
    iType = type;
    iValues = chrono.get(this, startMillis, endMillis);
}
 
Example #28
Source File: TestReadableIntervalConverter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testSetIntoPeriod_Object1() throws Exception {
    Interval i = new Interval(100L, 223L);
    MutablePeriod m = new MutablePeriod(PeriodType.millis());
    ReadableIntervalConverter.INSTANCE.setInto(m, i, null);
    assertEquals(0, m.getYears());
    assertEquals(0, m.getMonths());
    assertEquals(0, m.getWeeks());
    assertEquals(0, m.getDays());
    assertEquals(0, m.getHours());
    assertEquals(0, m.getMinutes());
    assertEquals(0, m.getSeconds());
    assertEquals(123, m.getMillis());
}
 
Example #29
Source File: Time_22_BasePeriod_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Creates a new period based on another using the {@link ConverterManager}.
 *
 * @param period  the period to convert
 * @param type  which set of fields this period supports, null means use type from object
 * @param chrono  the chronology to use, null means ISO default
 * @throws IllegalArgumentException if period is invalid
 * @throws IllegalArgumentException if an unsupported field's value is non-zero
 */
protected BasePeriod(Object period, PeriodType type, Chronology chrono) {
    super();
    PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
    type = (type == null ? converter.getPeriodType(period) : type);
    type = checkPeriodType(type);
    iType = type;
    if (this instanceof ReadWritablePeriod) {
        iValues = new int[size()];
        chrono = DateTimeUtils.getChronology(chrono);
        converter.setInto((ReadWritablePeriod) this, period, chrono);
    } else {
        iValues = new MutablePeriod(period, type, chrono).getValues();
    }
}
 
Example #30
Source File: Time_22_BasePeriod_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Creates a period from the given interval endpoints.
 *
 * @param startInstant  interval start, null means now
 * @param endInstant  interval end, null means now
 * @param type  which set of fields this period supports, null means standard
 * @throws IllegalArgumentException if period type is invalid
 */
protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) {
    super();
    type = checkPeriodType(type);
    if (startInstant == null && endInstant == null) {
        iType = type;
        iValues = new int[size()];
    } else {
        long startMillis = DateTimeUtils.getInstantMillis(startInstant);
        long endMillis = DateTimeUtils.getInstantMillis(endInstant);
        Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant);
        iType = type;
        iValues = chrono.get(this, startMillis, endMillis);
    }
}