Java Code Examples for java.time.Instant.equals()

The following are Jave code examples for showing how to use equals() of the java.time.Instant class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Chronetic   File: ChronoRange.java   View Source Code Vote up 6 votes
/**
 * Determines whether the given timestamp is within this ChronoRange.
 *
 * @param timestamp Instant to consider
 * @return whether or not this ChronoRange includes the given timestamp
 */
public boolean containsTime(Instant timestamp) {
    if (fullyConceptual) {
        return true;
    }

    for (Instant[] longArr : timestampRanges) {
        if ((timestamp.isAfter(longArr[0]) || timestamp.equals(longArr[0])) && (timestamp.isBefore(longArr[1]))) {
            return true;
        }
        if (timestamp.equals(longArr[1]) && patternEndLocalDateTime != null &&
                timestamp.equals(patternEndLocalDateTime.toInstant(ZoneOffset.UTC)) && includeEndingTimestamp) {
            return true;
        }
    }
    return false;
}
 
Example 2
Project: openjdk-jdk10   File: ZeroDate.java   View Source Code Vote up 6 votes
private static void testDate(byte[] data, int date, LocalDate expected) throws IOException {
    // set the datetime
    int endpos = data.length - ENDHDR;
    int cenpos = u16(data, endpos + ENDOFF);
    int locpos = u16(data, cenpos + CENOFF);
    writeU32(data, cenpos + CENTIM, date);
    writeU32(data, locpos + LOCTIM, date);

    // ensure that the archive is still readable, and the date is 1979-11-30
    Path path = Files.createTempFile("out", ".zip");
    try (OutputStream os = Files.newOutputStream(path)) {
        os.write(data);
    }
    try (ZipFile zf = new ZipFile(path.toFile())) {
        ZipEntry ze = zf.entries().nextElement();
        Instant actualInstant = ze.getLastModifiedTime().toInstant();
        Instant expectedInstant =
                expected.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
        if (!actualInstant.equals(expectedInstant)) {
            throw new AssertionError(
                    String.format("actual: %s, expected: %s", actualInstant, expectedInstant));
        }
    } finally {
        Files.delete(path);
    }
}
 
Example 3
Project: pure-bliss-with-pure-java-functions   File: OfflineDevicesJobImpl.java   View Source Code Vote up 6 votes
static Optional<Duration> calculateLastPassedThreshold(Instant start, Instant current, List<Duration> thresholds) {
    if (current.isBefore(start) || start.equals(current) || thresholds == null || thresholds.isEmpty()) {
        throw new IllegalArgumentException("Start must be before current and there should be at least 1 threshold");
    }

    Duration timePassed = Duration.between(start, current);

    if (timePassed.compareTo(thresholds.get(0)) <= 0) {
        return Optional.empty();
    }

    for (int i = 1; i < thresholds.size(); i++) {
        if (timePassed.compareTo(thresholds.get(i)) <= 0) {
            return Optional.of(thresholds.get(i - 1));
        }
    }

    return Optional.of(thresholds.get(thresholds.size() - 1));
}
 
Example 4
Project: pure-bliss-with-pure-java-functions   File: OfflineDevicesJobImpl.java   View Source Code Vote up 6 votes
/**
 * Calculates the last passed threshold given a start point and a current point in time plus a list of thresholds.
 * If the amount of time passed between the start and current instant is less than the first interval, it returns
 * empty.
 * If not, the amount is checked against each fixed interval and the calculated intervals after it. As soon
 * as the last passed interval has been determined, it will be returned.
 *
 * @param start      The start instant to compare the current instant with.
 * @param current    The current instant to compare with the starting point.
 * @param thresholds The list of fixed push notification thresholds.
 * @return The last passed threshold, or empty if no threshold has been passed yet.
 */
static Optional<Duration> calculateLastPassedThreshold(Instant start, Instant current, List<Duration> thresholds) {
    if (current.isBefore(start) || start.equals(current) || thresholds == null || thresholds.isEmpty()) {
        throw new IllegalArgumentException("Start must be before current and there should be at least 1 threshold");
    }

    Duration timePassed = Duration.between(start, current);

    if (timePassed.compareTo(thresholds.get(0)) <= 0) {
        return Optional.empty();
    }

    for (int i = 1; i < thresholds.size(); i++) {
        if (timePassed.compareTo(thresholds.get(i)) <= 0) {
            return Optional.of(thresholds.get(i - 1));
        }
    }

    return Optional.of(thresholds.get(thresholds.size() - 1));
}
 
Example 5
Project: Chronetic   File: ChronoSeries.java   View Source Code Vote up 5 votes
/**
 * Create a ChronoSeries from the given frequency information.
 *
 * @param minimumFrequency minimum frequency
 * @param maximumFrequency maximum frequency
 * @param frequencyUnit frequency unit
 * @param startInstant start timestamp
 * @param endInstant end stamp
 * @return ChronoSeries from the given frequency information
 */
@NotNull
public static ChronoSeries fromFrequency(long minimumFrequency, long maximumFrequency, @NotNull ChronoUnit frequencyUnit,
                                         @NotNull Instant startInstant, @NotNull Instant endInstant) {
    List<Instant> instants = new ArrayList<>();
    Instant itrTime = startInstant;
    while (itrTime.isBefore(endInstant) || itrTime.equals(endInstant)) {
        instants.add(itrTime);
        itrTime = itrTime.plus(RandomRegistry.getRandom().nextInt(
                (int) (maximumFrequency - minimumFrequency) + 1) + minimumFrequency, frequencyUnit);
    }
    return of(instants.toArray(new Instant[0]));
}
 
Example 6
Project: openjdk-jdk10   File: ZeroDate.java   View Source Code Vote up 5 votes
private static void testDate(byte[] data, int date, LocalDate expected) throws IOException {
    // set the datetime
    int endpos = data.length - ENDHDR;
    int cenpos = u16(data, endpos + ENDOFF);
    int locpos = u16(data, cenpos + CENOFF);
    writeU32(data, cenpos + CENTIM, date);
    writeU32(data, locpos + LOCTIM, date);

    // ensure that the archive is still readable, and the date is 1979-11-30
    Path path = Files.createTempFile("out", ".zip");
    try (OutputStream os = Files.newOutputStream(path)) {
        os.write(data);
    }
    URI uri = URI.create("jar:" + path.toUri());
    try (FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap())) {
        Path entry = fs.getPath("x");
        Instant actualInstant =
                Files.readAttributes(entry, BasicFileAttributes.class)
                        .lastModifiedTime()
                        .toInstant();
        Instant expectedInstant =
                expected.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
        if (!actualInstant.equals(expectedInstant)) {
            throw new AssertionError(
                    String.format("actual: %s, expected: %s", actualInstant, expectedInstant));
        }
    } finally {
        Files.delete(path);
    }
}
 
Example 7
Project: trading4j   File: M30.java   View Source Code Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localBase = instant1.atOffset(UTC).withSecond(0).withNano(0);
    final OffsetDateTime localStart = localBase.withMinute(localBase.getMinute() - localBase.getMinute() % 30);

    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusMinutes(30).toInstant();

    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 8
Project: trading4j   File: M5.java   View Source Code Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localBase = instant1.atOffset(UTC).withSecond(0).withNano(0);
    final OffsetDateTime localStart = localBase.withMinute(localBase.getMinute() - localBase.getMinute() % 5);

    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusMinutes(5).toInstant();

    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 9
Project: trading4j   File: M1.java   View Source Code Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localStart = instant1.atOffset(UTC).withSecond(0).withNano(0);
    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusMinutes(1).toInstant();
    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 10
Project: trading4j   File: M15.java   View Source Code Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localBase = instant1.atOffset(UTC).withSecond(0).withNano(0);
    final OffsetDateTime localStart = localBase.withMinute(localBase.getMinute() - localBase.getMinute() % 15);

    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusMinutes(15).toInstant();

    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 11
Project: trading4j   File: D1.java   View Source Code Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {

    final ZonedDateTime britishTime = instant1.atZone(BRITISH_TIME_ZONE);
    final DayOfWeek britishDay = britishTime.getDayOfWeek();

    final ZonedDateTime localBase = britishTime.withHour(0).withMinute(0).withSecond(0).withNano(0);

    final ZonedDateTime start;
    final ZonedDateTime end;

    if (britishDay == SUNDAY) {
        if (britishTime.isBefore(localBase.withHour(22))) {
            start = localBase;
            end = localBase.withHour(22);
        } else {
            start = localBase.withHour(22);
            end = localBase.plusDays(2);
        }
    } else if (britishDay == MONDAY) {
        start = localBase.minusDays(1).withHour(22);
        end = localBase.plusDays(1);
    } else {
        start = localBase;
        end = localBase.plusDays(1);
    }

    return instant2.equals(start.toInstant())
            || (instant2.isAfter(start.toInstant()) && instant2.isBefore(end.toInstant()));
}
 
Example 12
Project: trading4j   File: H1.java   View Source Code Vote up 5 votes
@Override
public boolean areInSameTimeFrame(final Instant instant1, final Instant instant2) {
    final OffsetDateTime localStart = instant1.atOffset(UTC).withMinute(0).withSecond(0).withNano(0);

    final Instant start = localStart.toInstant();
    final Instant startOfNext = localStart.plusHours(1).toInstant();

    return instant2.equals(start) || (instant2.isAfter(start) && instant2.isBefore(startOfNext));
}
 
Example 13
Project: jdk8u-jdk   File: JavatimeTest.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Throwable {
    int N = 10000;
    long t1970 = new java.util.Date(70, 0, 01).getTime();
    Random r = new Random();
    for (int i = 0; i < N; i++) {
        int days  = r.nextInt(50) * 365 + r.nextInt(365);
        long secs = t1970 + days * 86400 + r.nextInt(86400);
        int nanos = r.nextInt(NANOS_PER_SECOND);
        int nanos_ms = nanos / 1000000 * 1000000; // millis precision
        long millis = secs * 1000 + r.nextInt(1000);

        LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
        LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
        Instant inst = Instant.ofEpochSecond(secs, nanos);
        Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
        //System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);

        /////////// Timestamp ////////////////////////////////
        Timestamp ta = new Timestamp(millis);
        ta.setNanos(nanos);
        if (!isEqual(ta.toLocalDateTime(), ta)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ta.toLocalDateTime(), ta);
            throw new RuntimeException("FAILED: j.s.ts -> ldt");
        }
        if (!isEqual(ldt, Timestamp.valueOf(ldt))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ldt, Timestamp.valueOf(ldt));
            throw new RuntimeException("FAILED: ldt -> j.s.ts");
        }
        Instant inst0 = ta.toInstant();
        if (ta.getTime() != inst0.toEpochMilli() ||
            ta.getNanos() != inst0.getNano() ||
            !ta.equals(Timestamp.from(inst0))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            throw new RuntimeException("FAILED: j.s.ts -> instant -> j.s.ts");
        }
        inst = Instant.ofEpochSecond(secs, nanos);
        Timestamp ta0 = Timestamp.from(inst);
        if (ta0.getTime() != inst.toEpochMilli() ||
            ta0.getNanos() != inst.getNano() ||
            !inst.equals(ta0.toInstant())) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            throw new RuntimeException("FAILED: instant -> timestamp -> instant");
        }

        ////////// java.sql.Date /////////////////////////////
        // j.s.d/t uses j.u.d.equals() !!!!!!!!
        java.sql.Date jsd = new java.sql.Date(millis);
        if (!isEqual(jsd.toLocalDate(), jsd)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(jsd.toLocalDate(), jsd);
            throw new RuntimeException("FAILED: j.s.d -> ld");
        }
        LocalDate ld = ldt.toLocalDate();
        if (!isEqual(ld, java.sql.Date.valueOf(ld))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ld, java.sql.Date.valueOf(ld));
            throw new RuntimeException("FAILED: ld -> j.s.d");
        }
        ////////// java.sql.Time /////////////////////////////
        java.sql.Time jst = new java.sql.Time(millis);
        if (!isEqual(jst.toLocalTime(), jst)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(jst.toLocalTime(), jst);
            throw new RuntimeException("FAILED: j.s.t -> lt");
        }
        // millis precision
        LocalTime lt = ldt_ms.toLocalTime();
        if (!isEqual(lt, java.sql.Time.valueOf(lt))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(lt, java.sql.Time.valueOf(lt));
            throw new RuntimeException("FAILED: lt -> j.s.t");
        }
    }
    System.out.println("Passed!");
}
 
Example 14
Project: openjdk-jdk10   File: JavatimeTest.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Throwable {
    int N = 10000;
    long t1970 = new java.util.Date(70, 0, 01).getTime();
    Random r = new Random();
    for (int i = 0; i < N; i++) {
        int days  = r.nextInt(50) * 365 + r.nextInt(365);
        long secs = t1970 + days * 86400 + r.nextInt(86400);
        int nanos = r.nextInt(NANOS_PER_SECOND);
        int nanos_ms = nanos / 1000000 * 1000000; // millis precision
        long millis = secs * 1000 + r.nextInt(1000);

        LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
        LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
        Instant inst = Instant.ofEpochSecond(secs, nanos);
        Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
        //System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);

        /////////// Timestamp ////////////////////////////////
        Timestamp ta = new Timestamp(millis);
        ta.setNanos(nanos);
        if (!isEqual(ta.toLocalDateTime(), ta)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ta.toLocalDateTime(), ta);
            throw new RuntimeException("FAILED: j.s.ts -> ldt");
        }
        if (!isEqual(ldt, Timestamp.valueOf(ldt))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ldt, Timestamp.valueOf(ldt));
            throw new RuntimeException("FAILED: ldt -> j.s.ts");
        }
        Instant inst0 = ta.toInstant();
        if (ta.getTime() != inst0.toEpochMilli() ||
            ta.getNanos() != inst0.getNano() ||
            !ta.equals(Timestamp.from(inst0))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            throw new RuntimeException("FAILED: j.s.ts -> instant -> j.s.ts");
        }
        inst = Instant.ofEpochSecond(secs, nanos);
        Timestamp ta0 = Timestamp.from(inst);
        if (ta0.getTime() != inst.toEpochMilli() ||
            ta0.getNanos() != inst.getNano() ||
            !inst.equals(ta0.toInstant())) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            throw new RuntimeException("FAILED: instant -> timestamp -> instant");
        }

        ////////// java.sql.Date /////////////////////////////
        // j.s.d/t uses j.u.d.equals() !!!!!!!!
        java.sql.Date jsd = new java.sql.Date(millis);
        if (!isEqual(jsd.toLocalDate(), jsd)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(jsd.toLocalDate(), jsd);
            throw new RuntimeException("FAILED: j.s.d -> ld");
        }
        LocalDate ld = ldt.toLocalDate();
        if (!isEqual(ld, java.sql.Date.valueOf(ld))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ld, java.sql.Date.valueOf(ld));
            throw new RuntimeException("FAILED: ld -> j.s.d");
        }
        ////////// java.sql.Time /////////////////////////////
        java.sql.Time jst = new java.sql.Time(millis);
        if (!isEqual(jst.toLocalTime(), jst)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(jst.toLocalTime(), jst);
            throw new RuntimeException("FAILED: j.s.t -> lt");
        }
        // millis precision
        LocalTime lt = ldt_ms.toLocalTime();
        if (!isEqual(lt, java.sql.Time.valueOf(lt))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(lt, java.sql.Time.valueOf(lt));
            throw new RuntimeException("FAILED: lt -> j.s.t");
        }
    }
    System.out.println("Passed!");
}