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

The following examples show how to use java.time.Duration#toDays() . 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: GtfsStatisticsService.java    From gtfs-validator with MIT License 5 votes vote down vote up
/**
* A convenience method primarily written for pre-allocating objects of a reasonable size.
* Implementation result apparently varies based on JRE version. 
* Beware if used for validation 
*/
@Deprecated
@Override
public Integer getNumberOfDays() {
	Duration d = Duration.between(
			getCalendarServiceRangeStart().toInstant().atZone(getTimeZone()).toInstant()
			, getCalendarServiceRangeEnd().toInstant().atZone(getTimeZone()).toInstant());
	// zero indexed!
	return (int) d.toDays() +1;
}
 
Example 3
Source File: Durations.java    From digdag with Apache License 2.0 5 votes vote down vote up
public static String formatDuration(Duration duration)
{
    long d = duration.toDays();
    long h = duration.minusDays(d).toHours();
    long m = duration.minusDays(d).minusHours(h).toMinutes();
    long s = duration.minusDays(d).minusHours(h).minusMinutes(m).getSeconds();

    return Stream.of(
            d == 0 ? null : d + "d",
            h == 0 ? null : h + "h",
            m == 0 ? null : m + "m",
            s == 0 ? null : s + "s")
            .filter(v -> v != null)
            .collect(Collectors.joining(" "));
}
 
Example 4
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 5
Source File: EssentialsAPI.java    From EssentialsNK with GNU General Public License v3.0 5 votes vote down vote up
public boolean mute(Player player, Duration t) {
    if (t.isNegative() || t.isZero()) return false;
    // t>30 => (t!=30 && t>=30) => (t!=30 && t-30>=0) => (t!=30 && !(t-30<0))
    if (t.toDays() != 30 && !(t.minus(THIRTY_DAYS).isNegative())) return false; // t>30
    this.muteConfig.set(player.getName().toLowerCase(), Timestamp.valueOf(LocalDateTime.now().plus(t)).getTime() / 1000);
    this.muteConfig.save();
    return true;
}
 
Example 6
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 7
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 8
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 9
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 10
Source File: CoreMetrics.java    From styx with Apache License 2.0 5 votes vote down vote up
private static String formatTime(long timeInMilliseconds) {
    Duration duration = Duration.ofMillis(timeInMilliseconds);

    long days = duration.toDays();
    long hours = duration.minusDays(days).toHours();
    long minutes = duration.minusHours(duration.toHours()).toMinutes();

    return format("%dd %dh %dm", days, hours, minutes);
}
 
Example 11
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 12
Source File: PeriodFormats.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private static long periodAmount(TemporalUnit unit, Duration duration) {
  if (unit == ChronoUnit.DAYS) {
    return duration.toDays();
  } else if (unit == ChronoUnit.HOURS) {
    return duration.toHours();
  } else if (unit == ChronoUnit.MINUTES) {
    return duration.toMinutes();
  } else if (unit == ChronoUnit.SECONDS) {
    return duration.getSeconds();
  } else if (unit == ChronoUnit.MILLIS) {
    return duration.toMillis();
  } else {
    throw new IllegalArgumentException("Unsupported time unit: " + unit);
  }
}
 
Example 13
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 14
Source File: TimeUtils.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static long daysRoundingUp(Duration duration) {
    final long days = duration.toDays();
    return duration.equals(Duration.ofDays(days)) ? days : days + 1;
}
 
Example 15
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 getDaysDuration(Duration duration) {
  return duration.toDays();
}
 
Example 16
Source File: InsightsUtils.java    From Insights with Apache License 2.0 4 votes vote down vote up
public static Long getDurationBetweenDatesInDays(Long inputEpochMillis) {
	ZonedDateTime now = ZonedDateTime.now(zoneId);
	ZonedDateTime fromInput = ZonedDateTime.ofInstant(Instant.ofEpochMilli(inputEpochMillis), zoneId);
	Duration d = Duration.between(fromInput, now);
	return d.toDays();
}
 
Example 17
Source File: ClanHall.java    From L2jOrg with GNU General Public License v3.0 4 votes vote down vote up
public int getCostFailDay() {
    final Duration failDay = Duration.between(Instant.ofEpochMilli(paidUntil), Instant.now());
    return failDay.isNegative() ? 0 : (int) failDay.toDays();
}
 
Example 18
Source File: MemcachedCacheProperties.java    From memcached-spring-boot with Apache License 2.0 4 votes vote down vote up
private void validateExpiration(Duration expiration) {
    if (expiration == null || expiration.toDays() > 30) {
        throw new IllegalStateException("Invalid expiration. It should not be null or greater than 30 days.");
    }
}
 
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: PlayerEventHandler.java    From GriefDefender with MIT License 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerLogin(PlayerLoginEvent event) {
    GDTimings.PLAYER_LOGIN_EVENT.startTiming();
    final Player player = event.getPlayer();
    if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(player.getWorld().getUID())) {
        GDTimings.PLAYER_LOGIN_EVENT.stopTiming();
        return;
    }

    final boolean checkRestore = GriefDefenderPlugin.getGlobalConfig().getConfig().economy.rentSystem && GriefDefenderPlugin.getInstance().getWorldEditProvider() != null;
    final UUID worldUniqueId = event.getPlayer().getWorld().getUID();
    final UUID playerUniqueId = player.getUniqueId();
    final GDClaimManager claimWorldManager = this.dataStore.getClaimWorldManager(worldUniqueId);
    final Instant dateNow = Instant.now();
    for (Claim claim : claimWorldManager.getWorldClaims()) {
        if (claim.getType() != ClaimTypes.ADMIN && claim.getOwnerUniqueId().equals(playerUniqueId)) {
            claim.getData().setDateLastActive(dateNow);
            for (Claim subdivision : ((GDClaim) claim).children) {
                subdivision.getData().setDateLastActive(dateNow);
            }
            ((GDClaim) claim).getInternalClaimData().setRequiresSave(true);
            ((GDClaim) claim).getInternalClaimData().save();
        } else if (checkRestore && claim.getEconomyData() != null && claim.getEconomyData().isRented()) {
            for (UUID uuid : claim.getEconomyData().getRenters()) {
                if (player.getUniqueId().equals(uuid)) {
                    // check for rent expiration
                    final PaymentType paymentType = claim.getEconomyData().getPaymentType();
                    final int rentMax = claim.getEconomyData().getRentMaxTime();
                    final Instant rentStart = claim.getEconomyData().getRentStartDate();
                    if (rentStart != null) {
                        final Instant endDate = rentStart.plus(rentMax, ChronoUnit.DAYS);
                        final Duration duration = Duration.between(rentStart, endDate);
                        if (!duration.isNegative() && duration.toDays() <= GriefDefenderPlugin.getGlobalConfig().getConfig().economy.rentRestoreDayWarning) {
                            final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ECONOMY_CLAIM_RENTED_TIME_WARNING, ImmutableMap.of(
                                    "days", duration.toDays()
                                    ));
                            GriefDefenderPlugin.sendMessage(player, message);
                        }
                    }
                }
            }
        }
    }
    GDTimings.PLAYER_LOGIN_EVENT.stopTiming();
}