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

The following are Jave code examples for showing how to use toEpochMilli() 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.
Example 1
Project: vars-annotation   File: SnapTime.java   Source Code and License Vote up 6 votes
public String getTimecodeString() {
    Timecode placeholder;

    if (videoIndex.getTimecode().isPresent()) {             // Check timecode first
        placeholder = videoIndex.getTimecode().get();
    }
    else if (videoIndex.getElapsedTime().isPresent()) {     // If no timecode, try elapsed time
        Duration duration = videoIndex.getElapsedTime().get();
        double frames = duration.toMillis() / 10D; // centi-seconds
        placeholder = new Timecode(frames, 100D);
    }
    else {        // final case create name from date
        Instant timestamp = videoIndex.getTimestamp().get();
        double centisecs = timestamp.toEpochMilli() / 10D;
        placeholder = new Timecode(centisecs, 100D);
    }

    return placeholder.toString();
}
 
Example 2
Project: mid-tier   File: Event.java   Source Code and License Vote up 6 votes
/**
 * @param sid    a controlled human readable and url capable identifier
 * @param origin is a url pointing to the origin of the event
 */
public Event(String sid, URI origin, Instant time, String information, String category) {
    this.time = new Timestamp(time.toEpochMilli());
    this.transientTime = time;
    this.id = sid;
    this.origin = origin.getPath();
    this.information = information;
    this.category = category;
    tId = UUID.randomUUID().toString();
    // The semantic key might as well be generated as a hash value of the event values
    // for simplicity it is just a unique id here. The reason for having a technical
    // id here is the ability to merge og split events according to needs going forward.
    if (noSequence()) {
        sequence = time.toEpochMilli() + time.getNano();
    }
}
 
Example 3
Project: mid-tier   File: Event.java   Source Code and License Vote up 6 votes
/**
 * @param sid    a controlled human readable and url capable identifier
 * @param origin is a url pointing to the origin of the event
 */
public Event(String sid, URI origin, Instant time, String information, String category) {
    this.time = new Timestamp(time.toEpochMilli());
    this.transientTime = time;
    this.id = sid;
    this.origin = origin.getPath();
    this.information = information;
    this.category = category;
    tId = UUID.randomUUID().toString();
    // The semantic key might as well be generated as a hash value of the event values
    // for simplicity it is just a unique id here. The reason for having a technical
    // id here is the ability to merge og split events according to needs going forward.
    if (noSequence()) {
        sequence = time.toEpochMilli() + time.getNano();
    }
}
 
Example 4
Project: openjdk-jdk10   File: TCKClock_System.java   Source Code and License Vote up 5 votes
public void test_instant() {
    Clock system = Clock.systemUTC();
    assertEquals(system.getZone(), ZoneOffset.UTC);
    for (int i = 0; i < 10000; i++) {
        // assume can eventually get these within 10 milliseconds
        Instant instant = system.instant();
        long systemMillis = System.currentTimeMillis();
        if (systemMillis - instant.toEpochMilli() < 10) {
            return;  // success
        }
    }
    fail();
}
 
Example 5
Project: Pet-Supply-Store   File: TrainingSynchronizer.java   Source Code and License Vote up 5 votes
private static long toMillis(String date) {
	TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_LOCAL_DATE_TIME.parse(date);
	LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
	ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
	Instant instant = Instant.from(zonedDateTime);
	return instant.toEpochMilli();
}
 
Example 6
Project: rskj   File: Bridge.java   Source Code and License Vote up 5 votes
public Long getRetiringFederationCreationTime(Object[] args)
{
    logger.trace("getRetiringFederationCreationTime");

    Instant creationTime = bridgeSupport.getRetiringFederationCreationTime();

    if (creationTime == null) {
        // -1 is returned when no retiring federation
        return -1L;
    }

    // Return the creation time in milliseconds from the epoch
    return creationTime.toEpochMilli();
}
 
Example 7
Project: jdk8u-jdk   File: TCKClock_System.java   Source Code and License Vote up 5 votes
public void test_instant() {
    Clock system = Clock.systemUTC();
    assertEquals(system.getZone(), ZoneOffset.UTC);
    for (int i = 0; i < 10000; i++) {
        // assume can eventually get these within 10 milliseconds
        Instant instant = system.instant();
        long systemMillis = System.currentTimeMillis();
        if (systemMillis - instant.toEpochMilli() < 10) {
            return;  // success
        }
    }
    fail();
}
 
Example 8
Project: cakes   File: InstantDemo.java   Source Code and License Vote up 5 votes
/**
 * 获取时间戳
 */
@Test
public void testTimestamp() {
    Instant instant = Instant.now();

    // 获取毫秒时间, 时间戳
    long milli = instant.toEpochMilli();
    System.out.println(milli);
}
 
Example 9
Project: openjdk-jdk10   File: JavatimeTest.java   Source Code and License 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 10
Project: lams   File: DateTimeConverters.java   Source Code and License Vote up 4 votes
@Override
public Long convert(Instant source) {
	return source.toEpochMilli();
}
 
Example 11
Project: amanda   File: InstantConverter.java   Source Code and License Vote up 4 votes
@Override
public Timestamp convertToDatabaseColumn(Instant instant) {
    return instant == null ? null : new Timestamp(instant.toEpochMilli());
}
 
Example 12
Project: jdk8u-jdk   File: TestInstant.java   Source Code and License Vote up 4 votes
@Test(dataProvider="sampleEpochMillis")
public void test_epochMillis(String name, long millis) {
    Instant t1 = Instant.ofEpochMilli(millis);
    long m = t1.toEpochMilli();
    assertEquals(millis, m, name);
}
 
Example 13
Project: openjdk-jdk10   File: TestInstant.java   Source Code and License Vote up 4 votes
@Test(dataProvider="sampleEpochMillis")
public void test_epochMillis(String name, long millis) {
    Instant t1 = Instant.ofEpochMilli(millis);
    long m = t1.toEpochMilli();
    assertEquals(millis, m, name);
}
 
Example 14
Project: morpheus-core   File: LongCoding.java   Source Code and License Vote up 4 votes
@Override
public final long getCode(Instant value) {
    return value == null ? Long.MIN_VALUE : value.toEpochMilli();
}
 
Example 15
Project: openjdk-jdk10   File: XmlFormatterNanos.java   Source Code and License Vote up 4 votes
private static void testMatching(XMLFormatter formatter,
        LogRecord record,  Instant instant, long expectedNanos,
        boolean useInstant) {

    ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
    int zdtNanos = zdt.getNano();
    assertEquals(expectedNanos, zdtNanos, "ZonedDateTime.getNano()");

    String str = formatter.format(record);

    String match = "."+expectedNanos;
    if (str.contains(match) != useInstant) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string does not contain expected nanos: "
                + "\n\texpected match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    System.out.println("Found expected match for '"+match+"' in \n"+str);

    match = "<millis>"+instant.toEpochMilli()+"</millis>";
    if (!str.contains(match)) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string does not contain expected millis: "
                + "\n\texpected match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    System.out.println("Found expected match for '"+match+"' in \n"+str);

    match = "<nanos>";
    if (str.contains(match) != useInstant) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string "
                + (useInstant
                        ? "does not contain expected nanos: "
                        : "contains unexpected nanos: ")
                + "\n\t" + (useInstant ? "expected" : "unexpected")
                + " match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    match = "<nanos>"+getNanoAdjustment(record)+"</nanos>";
    if (str.contains(match) != useInstant) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string "
                + (useInstant
                        ? "does not contain expected nanos: "
                        : "contains unexpected nanos: ")
                + "\n\t" + (useInstant ? "expected" : "unexpected")
                + " match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    if (useInstant) {
        System.out.println("Found expected match for '"+match+"' in \n"+str);
    } else {
        System.out.println("As expected '"+match+"' is not present in \n"+str);
    }

    match = useInstant ? DateTimeFormatter.ISO_INSTANT.format(instant)
            : zdt.truncatedTo(ChronoUnit.SECONDS)
                    .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    match = "<date>"+match+"</date>";
    if (!str.contains(match)) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string does not contain expected date: "
                + "\n\texpected match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    System.out.println("Found expected match for '"+match+"' in \n"+str);

}
 
Example 16
Project: OpenJSharp   File: Date.java   Source Code and License Vote up 3 votes
/**
 * Obtains an instance of {@code Date} from an {@code Instant} object.
 * <p>
 * {@code Instant} uses a precision of nanoseconds, whereas {@code Date}
 * uses a precision of milliseconds.  The conversion will trancate any
 * excess precision information as though the amount in nanoseconds was
 * subject to integer division by one million.
 * <p>
 * {@code Instant} can store points on the time-line further in the future
 * and further in the past than {@code Date}. In this scenario, this method
 * will throw an exception.
 *
 * @param instant  the instant to convert
 * @return a {@code Date} representing the same point on the time-line as
 *  the provided instant
 * @exception NullPointerException if {@code instant} is null.
 * @exception IllegalArgumentException if the instant is too large to
 *  represent as a {@code Date}
 * @since 1.8
 */
public static Date from(Instant instant) {
    try {
        return new Date(instant.toEpochMilli());
    } catch (ArithmeticException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example 17
Project: jdk8u-jdk   File: Date.java   Source Code and License Vote up 3 votes
/**
 * Obtains an instance of {@code Date} from an {@code Instant} object.
 * <p>
 * {@code Instant} uses a precision of nanoseconds, whereas {@code Date}
 * uses a precision of milliseconds.  The conversion will trancate any
 * excess precision information as though the amount in nanoseconds was
 * subject to integer division by one million.
 * <p>
 * {@code Instant} can store points on the time-line further in the future
 * and further in the past than {@code Date}. In this scenario, this method
 * will throw an exception.
 *
 * @param instant  the instant to convert
 * @return a {@code Date} representing the same point on the time-line as
 *  the provided instant
 * @exception NullPointerException if {@code instant} is null.
 * @exception IllegalArgumentException if the instant is too large to
 *  represent as a {@code Date}
 * @since 1.8
 */
public static Date from(Instant instant) {
    try {
        return new Date(instant.toEpochMilli());
    } catch (ArithmeticException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example 18
Project: openjdk-jdk10   File: Date.java   Source Code and License Vote up 3 votes
/**
 * Obtains an instance of {@code Date} from an {@code Instant} object.
 * <p>
 * {@code Instant} uses a precision of nanoseconds, whereas {@code Date}
 * uses a precision of milliseconds.  The conversion will truncate any
 * excess precision information as though the amount in nanoseconds was
 * subject to integer division by one million.
 * <p>
 * {@code Instant} can store points on the time-line further in the future
 * and further in the past than {@code Date}. In this scenario, this method
 * will throw an exception.
 *
 * @param instant  the instant to convert
 * @return a {@code Date} representing the same point on the time-line as
 *  the provided instant
 * @exception NullPointerException if {@code instant} is null.
 * @exception IllegalArgumentException if the instant is too large to
 *  represent as a {@code Date}
 * @since 1.8
 */
public static Date from(Instant instant) {
    try {
        return new Date(instant.toEpochMilli());
    } catch (ArithmeticException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example 19
Project: cas-5.1.0   File: DateTimeUtils.java   Source Code and License Vote up 2 votes
/**
 * Gets DateTime for Instant.
 *
 * @param time Time object to be converted.
 * @return DateTime representing time
 */
public static DateTime dateTimeOf(final Instant time) {
    return new DateTime(time.toEpochMilli());
}
 
Example 20
Project: openjdk-jdk10   File: LogRecord.java   Source Code and License Vote up 2 votes
/**
 * Sets the instant that the event occurred.
 * <p>
 * If the given {@code instant} represents a point on the time-line too
 * far in the future or past to fit in a {@code long} milliseconds and
 * nanoseconds adjustment, then an {@code ArithmeticException} will be
 * thrown.
 *
 * @param instant the instant that the event occurred.
 *
 * @throws NullPointerException if {@code instant} is null.
 * @throws ArithmeticException if numeric overflow would occur while
 *         calling {@link Instant#toEpochMilli() instant.toEpochMilli()}.
 *
 * @since 9
 */
public void setInstant(Instant instant) {
    instant.toEpochMilli();
    this.instant = instant;
}