public static String formatDuration(long duration) { // Using Joda Time DateTime now = new DateTime(); // Now DateTime plus = now.plus(new Duration(duration * 1000)); // Define and calculate the interval of time Interval interval = new Interval(now.getMillis(), plus.getMillis()); Period period = interval.toPeriod(PeriodType.time()); // Define the period formatter for pretty printing String ampersand = " & "; PeriodFormatter pf = new PeriodFormatterBuilder().appendHours().appendSuffix(ds("hour"), ds("hours")) .appendSeparator(" ", ampersand).appendMinutes().appendSuffix(ds("minute"), ds("minutes")) .appendSeparator(ampersand).appendSeconds().appendSuffix(ds("second"), ds("seconds")).toFormatter(); return pf.print(period).trim(); }
private static PeriodType getPeriodType(OrgInterval.Unit unit) { switch (unit) { case HOUR: return PeriodType.hours(); case DAY: return PeriodType.days(); case WEEK: return PeriodType.weeks(); case MONTH: return PeriodType.months(); case YEAR: return PeriodType.years(); default: throw new IllegalArgumentException("Unknown unit " + unit); } }
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()); } }
@Test public void testToPeriodWithLowClosedHighOpenDate() { PointInTime start = new PointInTime(2000, 1, 2); PointInTime stop = new PointInTime(2001, 1, 1); Period expected = new Period(start.promote().getLow(), stop.promote().getHigh().subtractMilliseconds(1)); Period actual = new IntervalOfTime(start, stop).toPeriod(); assertThat(expected.getYears(), is(actual.getYears())); assertThat(expected.getMonths(), is(actual.getMonths())); assertThat(expected.getDays(), is(actual.getDays())); assertThat(expected.getHours(), is(actual.getHours())); assertThat(expected.getMinutes(), is(actual.getMinutes())); assertThat(expected.getSeconds(), is(actual.getSeconds())); assertThat(expected.getMillis(), is(actual.getMillis())); expected = new Period(start.promote().getLow(), stop.promote().getHigh().subtractMilliseconds(1), PeriodType.yearMonthDay()); actual = new IntervalOfTime(start, stop).toPeriod(PeriodType.yearMonthDay()); assertThat(expected.getYears(), is(actual.getYears())); assertThat(expected.getMonths(), is(actual.getMonths())); assertThat(expected.getDays(), is(actual.getDays())); assertThat(expected.getHours(), is(actual.getHours())); assertThat(expected.getMinutes(), is(actual.getMinutes())); assertThat(expected.getSeconds(), is(actual.getSeconds())); assertThat(expected.getMillis(), is(actual.getMillis())); }
@Test public void testToPeriodWithLowOpenHighClosedDate() { PointInTime start = new PointInTime(2000, 1, 2); PointInTime stop = new PointInTime(2001, 1, 1); IntervalOfTime iot = stop.promote(); PointInTime iota = iot.getHigh(); Period expected = new Period(start.promote().getLow().addMilliseconds(1), iota.subtractMilliseconds(1)); Period actual = new IntervalOfTime(start, stop, false, true, false).toPeriod(); assertThat(expected.getYears(), is(actual.getYears())); assertThat(expected.getMonths(), is(actual.getMonths())); assertThat(expected.getDays(), is(actual.getDays())); assertThat(expected.getHours(), is(actual.getHours())); assertThat(expected.getMinutes(), is(actual.getMinutes())); assertThat(expected.getSeconds(), is(actual.getSeconds())); assertThat(expected.getMillis(), is(actual.getMillis())); expected = new Period(start.promote().getLow().addMilliseconds(1), iota.subtractMilliseconds(1), PeriodType.yearMonthDay()); actual = new IntervalOfTime(start, stop, false, true, false).toPeriod(PeriodType.yearMonthDay()); assertThat(expected.getYears(), is(actual.getYears())); assertThat(expected.getMonths(), is(actual.getMonths())); assertThat(expected.getDays(), is(actual.getDays())); assertThat(expected.getHours(), is(actual.getHours())); assertThat(expected.getMinutes(), is(actual.getMinutes())); assertThat(expected.getSeconds(), is(actual.getSeconds())); assertThat(expected.getMillis(), is(actual.getMillis())); }
@Override public String toString() { StringBuffer sb = new StringBuffer(); String lf = "+%s => %s\n"; Iterator<Entry<Long, DATA>> entryItr = this.timeSeries.entrySet().iterator(); long last = 0; for (int i = 0; i < this.size(); i++) { Entry<Long, DATA> entry = entryItr.next(); long time = entry.getKey(); DATA data = entry.getValue(); Interval inter = new Interval(last,time); Period p = inter.toPeriod(PeriodType.yearDayTime()); sb.append(String.format(lf, p,data)); last =time; } return sb.toString(); }
public void testFormatStandard() { Period p = new Period(1, 2, 3, 4, 5, 6, 7, 8); assertEquals("P1Y2M3W4DT5H6M7.008S", ISOPeriodFormat.standard().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P1Y2M3W4DT5H6M7S", ISOPeriodFormat.standard().print(p)); p = new Period(0); assertEquals("PT0S", ISOPeriodFormat.standard().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("PT0M", ISOPeriodFormat.standard().print(p)); assertEquals("P1Y4DT5H6M7.008S", ISOPeriodFormat.standard().print(YEAR_DAY_PERIOD)); assertEquals("PT0S", ISOPeriodFormat.standard().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P1Y2M3W4D", ISOPeriodFormat.standard().print(DATE_PERIOD)); assertEquals("PT5H6M7.008S", ISOPeriodFormat.standard().print(TIME_PERIOD)); }
public void testFormatAlternateExtended() { Period p = new Period(1, 2, 3, 4, 5, 6 ,7, 8); assertEquals("P0001-02-04T05:06:07.008", ISOPeriodFormat.alternateExtended().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P0001-02-04T05:06:07", ISOPeriodFormat.alternateExtended().print(p)); p = new Period(0); assertEquals("P0000-00-00T00:00:00", ISOPeriodFormat.alternateExtended().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("P0000-00-00T00:00:00", ISOPeriodFormat.alternateExtended().print(p)); assertEquals("P0001-00-04T05:06:07.008", ISOPeriodFormat.alternateExtended().print(YEAR_DAY_PERIOD)); assertEquals("P0000-00-00T00:00:00", ISOPeriodFormat.alternateExtended().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P0001-02-04T00:00:00", ISOPeriodFormat.alternateExtended().print(DATE_PERIOD)); assertEquals("P0000-00-00T05:06:07.008", ISOPeriodFormat.alternateExtended().print(TIME_PERIOD)); }
public void testFormatAlternateWithWeeks() { Period p = new Period(1, 2, 3, 4, 5, 6 ,7, 8); assertEquals("P0001W0304T050607.008", ISOPeriodFormat.alternateWithWeeks().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P0001W0304T050607", ISOPeriodFormat.alternateWithWeeks().print(p)); p = new Period(0); assertEquals("P0000W0000T000000", ISOPeriodFormat.alternateWithWeeks().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("P0000W0000T000000", ISOPeriodFormat.alternateWithWeeks().print(p)); assertEquals("P0001W0004T050607.008", ISOPeriodFormat.alternateWithWeeks().print(YEAR_DAY_PERIOD)); assertEquals("P0000W0000T000000", ISOPeriodFormat.alternateWithWeeks().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P0001W0304T000000", ISOPeriodFormat.alternateWithWeeks().print(DATE_PERIOD)); assertEquals("P0000W0000T050607.008", ISOPeriodFormat.alternateWithWeeks().print(TIME_PERIOD)); }
public static String toAge(Date from, Date to) { if (from == null || to == null) return "N/A"; final Period period = new Period(from.getTime(), to.getTime()); DurationFieldType[] dtf = new ArrayList<DurationFieldType>() {{ add(DurationFieldType.years()); add(DurationFieldType.months()); add(DurationFieldType.days()); if (period.getYears() == 0 && period.getMonths() == 0 && period.getDays() == 0) { add(DurationFieldType.hours()); add(DurationFieldType.minutes()); } }}.toArray(new DurationFieldType[0]); PeriodFormatter pf = PeriodFormat.getDefault(); return pf.print(period.normalizedStandard(PeriodType.forFields(dtf))); }
public void testFormatAlternateExtendedWithWeeks() { Period p = new Period(1, 2, 3, 4, 5, 6 ,7, 8); assertEquals("P0001-W03-04T05:06:07.008", ISOPeriodFormat.alternateExtendedWithWeeks().print(p)); p = new Period(1, 2, 3, 4, 5, 6 ,7, 0); assertEquals("P0001-W03-04T05:06:07", ISOPeriodFormat.alternateExtendedWithWeeks().print(p)); p = new Period(0); assertEquals("P0000-W00-00T00:00:00", ISOPeriodFormat.alternateExtendedWithWeeks().print(p)); p = new Period(0, PeriodType.standard().withMillisRemoved().withSecondsRemoved()); assertEquals("P0000-W00-00T00:00:00", ISOPeriodFormat.alternateExtendedWithWeeks().print(p)); assertEquals("P0001-W00-04T05:06:07.008", ISOPeriodFormat.alternateExtendedWithWeeks().print(YEAR_DAY_PERIOD)); assertEquals("P0000-W00-00T00:00:00", ISOPeriodFormat.alternateExtendedWithWeeks().print(EMPTY_YEAR_DAY_PERIOD)); assertEquals("P0001-W03-04T00:00:00", ISOPeriodFormat.alternateExtendedWithWeeks().print(DATE_PERIOD)); assertEquals("P0000-W00-00T05:06:07.008", ISOPeriodFormat.alternateExtendedWithWeeks().print(TIME_PERIOD)); }
public static String getDiffFormatted(Date from, Date to) { Duration duration = new Duration(to.getTime() - from.getTime()); // in // milliseconds PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever()// .appendWeeks().appendSuffix("w").appendSeparator(" ")// .appendDays().appendSuffix("d").appendSeparator(" ")// .appendHours().appendSuffix("h").appendSeparator(" ")// .appendMinutes().appendSuffix("m").appendSeparator(" ")// .appendSeconds().appendSuffix("s")// .toFormatter(); String fullTimeAgo = formatter.print(duration.toPeriod(PeriodType.yearMonthDayTime())); return Arrays.stream(fullTimeAgo.split(" ")).limit(2).collect(Collectors.joining(" ")); }
/** * Gets all occurrences of an event time * * @param fromTime the from time * @return list of occurrences */ @JsonIgnore public List<ParsedEventData> getOccurrences(final long fromTime) { List<ParsedEventData> parsedResults = new ArrayList<>(); if (getStartTime() == null) { return parsedResults; } final long startTime = getStartTime().getMillis(); if (startTime >= fromTime) { parsedResults.add(generateParsedEventData(startTime, getDuration(), event.getId())); } if ((getRepeatTime() != null) && (getRepeatTime().normalizedStandard(PeriodType.hours()).getHours() >= 24)) { final long finalTime = DateTime.now().plusWeeks(6).getMillis(); final long lastTime = (getRepeatEnd() != null) ? getRepeatEnd().getMillis() : finalTime; final long newLastTime = lastTime <= finalTime ? lastTime : finalTime; final long timeDifference = newLastTime - startTime; if (timeDifference > 0) { final long repeatTime = getRepeatTime().normalizedStandard(PeriodType.millis()).getMillis(); final int repeatOccurrences = (int) Math.floor((double) timeDifference / (double) repeatTime); for (int i = 1; i <= Math.min(repeatOccurrences, 10); i++) { final long occurrenceTime = startTime + (repeatTime * i); if (occurrenceTime >= fromTime) { parsedResults.add(generateParsedEventData( occurrenceTime, getDuration(), event.getId())); } } } } return parsedResults; }
/** * Format the duration between since and until to a human readable string * * @param since Start DateTime * @param until End DateTime * @return A formatted string describing the time between since and until */ public String timeQuantityBetween(DateTime since, DateTime until) { long diff = new Duration(since, until).getMillis(); if (diff <= 1000) { return "0 " + i18n.getString("TimeUnit.seconds"); } if (diff < MILLIS_IN_MONTH) { return timeStringSmallScale(new Period(since, until, PeriodType.dayTime())); } else { return timeStringLargeScale(new Period(since, until, PeriodType.yearMonthDay())); } }
/** * Creates a Joda duration/period object * * @param date object that represents the duration of the period through milisseconds */ private void initializeDuration(Date date) { // Get duration from Date mDuration = new Duration(date.getTime()); // Get period final DurationFieldType[] durationFields = new DurationFieldType[]{DurationFieldType.weeks(), DurationFieldType.days(), DurationFieldType.hours(), DurationFieldType.minutes()}; mPeriod = mDuration.toPeriod(PeriodType.forFields(durationFields)).normalizedStandard(); updatePeriod(); }
@Nonnull public static Period calculateAge(@Nonnull final LocalDate beginDate, @Nonnull final DateTime endDateTime) { final DateTime start = beginDate.toDateTimeAtStartOfDay(); return new Duration(start, endDateTime).toPeriodFrom(start, PeriodType.years()); }
@Override public Period random() { return new Period(RandomData.randomLong(0, 1000), RandomData.random( Arrays.asList( PeriodType.millis(), PeriodType.seconds(), PeriodType.minutes(), PeriodType.hours(), PeriodType.days(), PeriodType.weeks(), PeriodType.months(), PeriodType.years() ))); }
public static Age calculateAge(Calendar birthDate) { LocalDate birthdate = LocalDate.fromCalendarFields(birthDate); LocalDate now = new LocalDate(); //Today's date Period period = new Period(birthdate, now, PeriodType.yearMonthDay()); return new Age(period.getDays(),period.getMonths(),period.getYears()); }
public String getLeft(int next, boolean showsecs) { LocalDateTime date = getTimeCal(null, next); Period period = new Period(LocalDateTime.now(), date, PeriodType.dayTime()); if (showsecs) { return Utils.toArabicNrs(PERIOD_FORMATTER_HMS.print(period)); } else if (Prefs.isDefaultWidgetMinuteType()) { return Utils.toArabicNrs(PERIOD_FORMATTER_HM.print(period)); } else { period = period.withFieldAdded(DurationFieldType.minutes(), 1); return Utils.toArabicNrs(PERIOD_FORMATTER_HM.print(period)); } }
public float getPassedPart() { int i = getNext(); LocalDateTime date1 = getTimeCal(null, i - 1); LocalDateTime date2 = getTimeCal(null, i); Period period = new Period(date1, date2, PeriodType.minutes()); float total = period.getMinutes(); float passed = total - getLeftMinutes(i); return passed / total; }
/** * 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); } }
/** * 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); }
/** * Creates a period from the given duration and end point. * * @param duration the duration of the interval, null means zero-length * @param endInstant the interval end, null means now * @param type which set of fields this period supports, null means standard */ protected BasePeriod(ReadableDuration duration, ReadableInstant endInstant, PeriodType type) { super(); type = checkPeriodType(type); long durationMillis = DateTimeUtils.getDurationMillis(duration); long endMillis = DateTimeUtils.getInstantMillis(endInstant); long startMillis = FieldUtils.safeSubtract(endMillis, durationMillis); Chronology chrono = DateTimeUtils.getInstantChronology(endInstant); iType = type; iValues = chrono.get(this, startMillis, endMillis); }
/** * Creates a period from the given millisecond duration with the standard period type * and ISO rules, ensuring that the calculation is performed with the time-only period type. * <p> * The calculation uses the hour, minute, second and millisecond fields. * * @param duration the duration, in milliseconds */ protected BasePeriod(long duration) { super(); // bug [3264409] // calculation uses period type from a period object (bad design) // thus we use a dummy period object with the time type iType = PeriodType.standard(); int[] values = ISOChronology.getInstanceUTC().get(DUMMY_PERIOD, duration); iValues = new int[8]; System.arraycopy(values, 0, iValues, 4, 4); }
/** * 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(); } }
/** * 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; }
@Override public int getItemCount() { if (currentDate == null || startDate == null || endDate == null) { return 0; } else { Period period = new Period(startDate, endDate, PeriodType.days()); return period.getDays() + 7; } }
public int getPositionFromDate(LocalDate date) { if (date == null || date.isBefore(startDate) || date.isAfter(endDate)) { return 0; } else { Period period = new Period(startDate, date, PeriodType.days()); return period.getDays(); } }
ProjectTime getTimeLeft(DateTime now) { if (now.isAfter(deadline)) { // TODO: add successful. return new ProjectTime("ENDED", deadline.toString()); } Period period = new Period(now, deadline, PeriodType.dayTime()); return PeriodToStringConverter.periodToProjectTime(period); }
/** * {@inheritDoc} */ @Override public String format(Number value) { if (value == null) { return null; } try { return formatter.print(new Period(0, value.longValue(), PeriodType.dayTime())); } catch (Throwable t) { return null; } }
/** * Calculates the length of the time the interface has been running. * @return the running time, or Period. ZERO if not currently running */ @MonitorableStatusValue( name = "elapsed_running_time", description = "The amount of time the interface has been running." ) public Period calculateRunningTime( ) { if( stopTime == null ) { return new Period( startTime, new DateTime( DateTimeZone.UTC ), PeriodType.standard( ) ); } else { return Period.ZERO; } }