Java Code Examples for java.time.Duration#toMinutes()

The following examples show how to use java.time.Duration#toMinutes() . 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: EssentialsAPI.java    From EssentialsNK with GNU General Public License v3.0 6 votes vote down vote up
public String getDurationString(Duration duration) {
    if (duration == null) return "null";
    long d = duration.toDays();
    long h = duration.toHours() % 24;
    long m = duration.toMinutes() % 60;
    long s = duration.getSeconds() % 60;
    String d1 = "", h1 = "", m1 = "", s1 = "";
    //Singulars and plurals. Maybe necessary for English or other languages. 虽然中文似乎没有名词的单复数 -- lmlstarqaq
    if (d > 1) d1 = Language.translate("commands.generic.days", d);
    else if (d > 0) d1 = Language.translate("commands.generic.day", d);
    if (h > 1) h1 = Language.translate("commands.generic.hours", h);
    else if (h > 0) h1 = Language.translate("commands.generic.hour", h);
    if (m > 1) m1 = Language.translate("commands.generic.minutes", m);
    else if (m > 0) m1 = Language.translate("commands.generic.minute", m);
    if (s > 1) s1 = Language.translate("commands.generic.seconds", s);
    else if (s > 0) s1 = Language.translate("commands.generic.second", s);
    //In some languages, times are read from SECONDS to HOURS, which should be noticed.
    return Language.translate("commands.generic.time.format", d1, h1, m1, s1).trim().replaceAll(" +", " ");
}
 
Example 2
Source File: OeeEventTrendController.java    From OEE-Designer with MIT License 6 votes vote down vote up
private XYChart.Data<Number, Number> createProductionPoint(OeeEvent event) throws Exception {
	Duration delta = computeDeltaTime(event);
	Long deltaMinutes = delta.toMinutes();

	Quantity produced = event.getQuantity();

	// convert to good UOM if necessary
	Equipment equipment = event.getEquipment();
	Material material = event.getMaterial();

	EquipmentMaterial eqm = equipment.getEquipmentMaterial(material);
	UnitOfMeasure uom = eqm.getRunRateUOM().getDividend();

	if (!produced.getUOM().equals(uom)) {
		produced = produced.convert(uom);
	}

	Double value = new Double(produced.getAmount());
	return new XYChart.Data<>(deltaMinutes.intValue(), value);
}
 
Example 3
Source File: TimeDiff.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Prints the duration in the format HH:MM:ss.SSS
 * 
 * @param diffMillis Duration expressed in milliseconds
 *
 * @return The formatted output
 */
public static String printDuration(long diffMillis) {
	Duration duration = Duration.of(diffMillis, ChronoUnit.MILLIS);

	long millis = duration.toMillis() % 1000;
	long minutes = duration.toMinutes() % 60;
	long seconds = (duration.toMillis() / 1000) % 60;
	long hours = duration.toMinutes() / 60;
	StringBuffer out = new StringBuffer();
	if (hours > 0) {
		out.append(StringUtils.leftPad(Long.toString(hours), 2, '0'));
		out.append(":");
	}
	if (minutes > 0 || hours > 0) {
		out.append(StringUtils.leftPad(Long.toString(minutes), 2, '0'));
		out.append(":");
	}
	out.append(StringUtils.leftPad(Long.toString(seconds), 2, '0'));
	out.append(".");
	out.append(StringUtils.leftPad(Long.toString(millis), 3, '0'));
	return out.toString();
}
 
Example 4
Source File: WebTemplateFunctions.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
public String fromNow(OffsetDateTime timestamp, String language) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d", Locale.forLanguageTag(language));
    Duration duration = Duration.between(timestamp, OffsetDateTime.now());
    long seconds = duration.getSeconds();
    if (seconds <= 0) {
        return timestamp.format(formatter);
    }
    if (seconds - 60 < 0) {
        return String.format("1 %s", i18n("timeInterval.minuteBefore", language));
    }
    long minutes = duration.toMinutes();
    if (minutes - 60 < 0) {
        return String.format("%d %s", minutes, i18n("timeInterval.minutesBefore", language));
    }
    long hours = duration.toHours();
    if (hours - 2 < 0) {
        return String.format("1 %s", i18n("timeInterval.hourBefore", language));
    }
    if (hours - 24 < 0) {
        return String.format("%d %s", hours, i18n("timeInterval.hoursBefore", language));
    }
    return timestamp.format(formatter);
}
 
Example 5
Source File: IssuesReportListener.java    From pitest-descartes with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String getStringTime() {
    //TODO: Is there a way to have this code in the template?

    Duration elapsed = Duration.ofMillis(System.currentTimeMillis() - arguments.getStartTime());
    String[] units = {"day", "hour", "minute", "second"};
    long[] parts = { elapsed.toDays(), elapsed.toHours() % 24, elapsed.toMinutes() % 60, elapsed.getSeconds() % 60};
    StringBuilder result = new StringBuilder();
    for(int i=0; i < parts.length; i++) {
        if(parts[i] == 0) continue;
        result.append(parts[i]).append(" ").append(units[i]);
        if(parts[i] > 1)
            result.append("s");
        result.append(" ");
    }
    if(result.length() == 0)
        return "less than one second";
    return result.substring(0, result.length() - 1);
}
 
Example 6
Source File: Song.java    From MusicPlayer with MIT License 5 votes vote down vote up
/**
 * Constructor for the song class.
 *
 * @param id
 * @param title
 * @param artist
 * @param album
 * @param length
 * @param trackNumber
 * @param discNumber
 * @param playCount
 * @param playDate
 * @param location
 */
public Song(int id, String title, String artist, String album, Duration length,
            int trackNumber, int discNumber, int playCount, LocalDateTime playDate, String location) {

    if (title == null) {
        Path path = Paths.get(location);
        String fileName = path.getFileName().toString();
        title = fileName.substring(0, fileName.lastIndexOf('.'));
    }

    if (album == null) {
        album = "Unknown Album";
    }

    if (artist == null) {
        artist = "Unknown Artist";
    }

    this.id = id;
    this.title = new SimpleStringProperty(title);
    this.artist = new SimpleStringProperty(artist);
    this.album = new SimpleStringProperty(album);
    this.lengthInSeconds = length.getSeconds();
    long seconds = length.getSeconds() % 60;
    this.length = new SimpleStringProperty(length.toMinutes() + ":" + (seconds < 10 ? "0" + seconds : seconds));
    this.trackNumber = trackNumber;
    this.discNumber = discNumber;
    this.playCount = new SimpleIntegerProperty(playCount);
    this.playDate = playDate;
    this.location = location;
    this.playing = new SimpleBooleanProperty(false);
    this.selected = new SimpleBooleanProperty(false);
}
 
Example 7
Source File: HumanDuration.java    From extract with MIT License 5 votes vote down vote up
/**
 * Convert the duration to a string of the same format that is accepted by {@link #parse(String)}.
 *
 * @return A formatted string representation of the duration.
 */
public static String format(final Duration duration) {
	long value = duration.toMillis();

	if (value >= 1000) {
		value = duration.getSeconds();
	} else {
		return String.format("%sms", value);
	}

	if (value >= 60) {
		value = duration.toMinutes();
	} else {
		return String.format("%ss", value);
	}

	if (value >= 60) {
		value = duration.toHours();
	} else {
		return String.format("%sm", value);
	}

	if (value >= 24) {
		value = duration.toDays();
	} else {
		return String.format("%sh", value);
	}

	return String.format("%sd", value);
}
 
Example 8
Source File: PostgreSQLIntervalType.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
@Override
protected void set(PreparedStatement st, Duration value, int index, SharedSessionContractImplementor session) throws SQLException {
    if (value == null) {
        st.setNull(index, Types.OTHER);
    } else {
        final int days = (int) value.toDays();
        final int hours = (int) (value.toHours() % 24);
        final int minutes = (int) (value.toMinutes() % 60);
        final double seconds = value.getSeconds() % 60;
        st.setObject(index, new PGInterval(0, 0, days, hours, minutes, seconds));
    }
}
 
Example 9
Source File: OracleIntervalDayToSecondType.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
@Override
protected void set(PreparedStatement st, Duration value, int index, SharedSessionContractImplementor session) throws SQLException {
    if (value == null) {
        st.setNull(index, SQL_COLUMN_TYPE);
    } else {
        final int days = (int) value.toDays();
        final int hours = (int) (value.toHours() % 24);
        final int minutes = (int) (value.toMinutes() % 60);
        final int seconds = (int) (value.getSeconds() % 60);

        st.setString(index, String.format(INTERVAL_TOKENS, days, hours, minutes, seconds));
    }
}
 
Example 10
Source File: TimeWheel.java    From JavaBase with MIT License 5 votes vote down vote up
private boolean insertWheel(String id, Duration delay) {
  long days = delay.toDays();
  if (days > 30) {
    log.warn("out of timeWheel max delay bound");
    return false;
  }

  long current = System.currentTimeMillis();
  long delayMills = delay.toMillis();
  TaskNode node = new TaskNode(id, null, current, delayMills);
  if (days > 0) {
    return insertWheel(ChronoUnit.DAYS, this.currentDay.get() + days, node);
  }

  long hours = delay.toHours();
  if (hours > 0) {
    return insertWheel(ChronoUnit.HOURS, this.currentHour.get() + hours, node);
  }

  long minutes = delay.toMinutes();
  if (minutes > 0) {
    return insertWheel(ChronoUnit.MINUTES, this.currentMinute.get() + minutes, node);
  }

  long seconds = delay.getSeconds();
  // TODO expire too long time
  if (seconds >= -10 && seconds <= 1) {
    return insertWheel(ChronoUnit.SECONDS, this.currentSecond.get() + 1, node);
  }
  if (seconds > 1) {
    return insertWheel(ChronoUnit.SECONDS, this.currentSecond.get() + seconds, node);
  }

  log.warn("task is expire: id={} delay={}", id, delay);
  return false;
}
 
Example 11
Source File: StringFormatUtils.java    From datakernel with Apache License 2.0 5 votes vote down vote up
public static String formatDuration(Duration value) {
	if (value.isZero()) {
		return "0 seconds";
	}
	String result = "";
	long days, hours, minutes, seconds, nano, milli;
	days = value.toDays();
	if (days != 0) {
		result += days + " days ";
	}
	hours = value.toHours() - days * 24;
	if (hours != 0) {
		result += hours + " hours ";
	}
	minutes = value.toMinutes() - days * 1440 - hours * 60;
	if (minutes != 0) {
		result += minutes + " minutes ";
	}
	seconds = value.getSeconds() - days * 86400 - hours * 3600 - minutes * 60;
	if (seconds != 0) {
		result += seconds + " seconds ";
	}
	nano = value.getNano();
	milli = (nano - nano % 1000000) / 1000000;
	if (milli != 0) {
		result += milli + " millis ";
	}
	nano = nano % 1000000;
	if (nano != 0) {
		result += nano + " nanos ";
	}
	return result.trim();
}
 
Example 12
Source File: OeeEventTrendController.java    From OEE-Designer with MIT License 5 votes vote down vote up
private XYChart.Data<Number, String> createAvailabilityPoint(OeeEvent event) {
	Duration delta = computeDeltaTime(event);
	Long deltaMinutes = delta.toMinutes();

	TimeLoss loss = event.getReason().getLossCategory();

	return new XYChart.Data<>(deltaMinutes.intValue(), loss.toString());
}
 
Example 13
Source File: DashboardController.java    From OEE-Designer with MIT License 5 votes vote down vote up
private double toDouble(Duration duration) {
	long value = 0;
	if (timeUnit.equals(Unit.SECOND)) {
		value = duration.getSeconds();
	} else if (timeUnit.equals(Unit.MINUTE)) {
		value = duration.toMinutes();
	} else if (timeUnit.equals(Unit.HOUR)) {
		value = duration.toHours();
	} else if (timeUnit.equals(Unit.DAY)) {
		value = duration.toDays();
	}
	return value;
}
 
Example 14
Source File: Utilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static String describeDuration(Duration d) {
  if (d.toDays() > 2) {
    return String.format("%s days", d.toDays());
  } else if (d.toHours() > 2) {
    return String.format("%s hours", d.toHours());
  } else if (d.toMinutes() > 2) {
    return String.format("%s mins", d.toMinutes());
  } else {
    return String.format("%s ms", d.toMillis());
  }
}
 
Example 15
Source File: DefaultAggregationService.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
protected static String durationFormat(Duration duration) {
    String durationStr = duration.toString();
    if (durationStr.contains("S")) {
        return duration.toMillis() / 1000 + "s";
    } else if (!durationStr.contains("S") && durationStr.contains("M")) {
        return duration.toMinutes() + "m";
    } else if (!durationStr.contains("S") && !durationStr.contains("M")) {
        if (duration.toHours() % 24 == 0) {
            return duration.toDays() + "d";
        } else {
            return duration.toHours() + "h";
        }
    }
    throw new UnsupportedOperationException("不支持的时间周期:" + duration.toString());
}
 
Example 16
Source File: JsonUtils.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
@Override
public JsonElement serialize(Duration duration, Type type, JsonSerializationContext context) {
    synchronized (this) {
        return new JsonPrimitive(duration.toMinutes());
    }
}
 
Example 17
Source File: DurationTool.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
public static long getMinutesDuration(Duration duration) {
  return duration.toMinutes();
}
 
Example 18
Source File: DurationTest.java    From JavaBase with MIT License 4 votes vote down vote up
private String format(Duration duration) {
  return duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds() % 60;
}
 
Example 19
Source File: BusinessCalendarImpl.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
protected String adoptISOFormat(String timeExpression) {

        try {
            Duration p = null;
            if (DateTimeUtils.isPeriod(timeExpression)) {
                p = Duration.parse(timeExpression);
            } else if (DateTimeUtils.isNumeric(timeExpression)) {
                p = Duration.of(Long.valueOf(timeExpression), ChronoUnit.MILLIS);
            } else {
                OffsetDateTime dateTime = OffsetDateTime.parse(timeExpression, DateTimeFormatter.ISO_DATE_TIME);
                p = Duration.between(OffsetDateTime.now(), dateTime);
            }

            long days = p.toDays();
            long hours = p.toHours() % 24;
            long minutes = p.toMinutes() % 60;
            long seconds = p.getSeconds() % 60;
            long milis = p.toMillis() % 1000;

            StringBuffer time = new StringBuffer();
            if (days > 0) {
                time.append(days + "d");
            }
            if (hours > 0) {
                time.append(hours + "h");
            }
            if (minutes > 0) {
                time.append(minutes + "m");
            }
            if (seconds > 0) {
                time.append(seconds + "s");
            }
            if (milis > 0) {
                time.append(milis + "ms");
            }

            return time.toString();
        } catch (Exception e) {
            return timeExpression;
        }
    }
 
Example 20
Source File: VCardManager.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
 * Attempts to load
 *
 * @param jid the jid of the user.
 * @return the VCard if found, otherwise null.
 */
private VCard loadFromFileSystem(BareJid jid) {
	if (jid == null) {
		return null;
	}
	
    // Unescape JID
    String fileName = Base64.encodeBytes(jid.toString().getBytes());

    // remove tab
    fileName   = fileName.replaceAll("\t", "");
    // remove new line (Unix)
    fileName          = fileName.replaceAll("\n", "");
    // remove new line (Windows)
    fileName          = fileName.replaceAll("\r", "");
    
    final File vcardFile = new File(vcardStorageDirectory, fileName);
    if (!vcardFile.exists()) {
        return null;
    }

    final VCard vcard;
    try ( final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(vcardFile), "UTF-8")) )
    {
        // Otherwise load from file system.
        VCardProvider provider = new VCardProvider();
        parser.setInput( in );

        // Skip forward until we're at <vCard xmlns='vcard-temp'>
        while ( !( parser.getEventType() == XmlPullParser.START_TAG && VCard.ELEMENT.equals( parser.getName() ) && VCard.NAMESPACE.equals( parser.getNamespace() ) ) )
        {
            parser.next();
        }

        vcard = provider.parse( parser );
    }
    catch (Exception e) {
        Log.warning("Unable to load vCard for " + jid, e);
        vcardFile.delete();
        return null;
    }

    addVCard(jid, vcard);

    // Check to see if the file is older 60 minutes. If so, reload.
    final String timestamp = vcard.getField( "timestamp" );
    if ( timestamp != null )
    {
        final Duration duration = Duration.between( Instant.ofEpochMilli( Long.parseLong( timestamp ) ), Instant.now() );
        if ( duration.toMinutes() >= 60 )
        {
            addToQueue( jid );
        }
    }

    return vcard;
}