Java Code Examples for java.time.LocalDateTime#ofEpochSecond()

The following examples show how to use java.time.LocalDateTime#ofEpochSecond() . 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: LocalDateTimeTest.java    From java-tutorial with Apache License 2.0 6 votes vote down vote up
/**
	 * 程序执行入口.
	 *
	 * @param args 命令行参数
	 */
	public static void main(String[] args) {

		LocalDateTime today = LocalDateTime.now(); // |\longremark{获得当前的日期时间对象}|
		System.out.println("Current DateTime=" + today);

		//Current Date using LocalDate and LocalTime
		today = LocalDateTime.of(LocalDate.now(), LocalTime.now());// |\longremark{根据给定的LocalDate和LocalTime创建日期时间对象}|
		System.out.println("Current DateTime=" + today);

		LocalDateTime specificDate = LocalDateTime.of(2014, 1, 1, 10, 10, 30);// |\longremark{根据给定的日期和时间创建日期时间对象}|
		System.out.println("Specific Date=" + specificDate);

		LocalDateTime todayShanghai = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));// |\longremark{根据给定的时区创建日期时间对象}|
		System.out.println("Current Date in CST=" + todayShanghai);

		LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);// |\longremark{从1970-1-1开始计算的日期时间对象}|
		System.out.println("10000th second time from 01/01/1970= " + dateFromBase);

//		LocalDateTime test1 = LocalDateTime.of(LocalDate.now(), null);
//		System.out.println("test1:" + test1);

	}
 
Example 2
Source File: BaseController.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
/**
 * 获取请求中说有的请求参数,并转换成Map
 * @return
 */
protected Map<String,Object> getParams()  {
    Map<String,Object> map = new HashMap<>(16);
    Enumeration em =  this.request.getParameterNames();
    while (em.hasMoreElements()){
        String key = (String) em.nextElement();
        Object value = this.request.getParameter(key);

        if(value!=null){
            if("startTime".equals(key) || "endTime".equals(key)){
                value = LocalDateTime.ofEpochSecond(Long.parseLong(String.valueOf(value))/1000,0, ZoneOffset.ofHours(8));
            }
            map.put(key,value);
        }
    }
    return map;
}
 
Example 3
Source File: S7Test.java    From mokka7 with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testSetDateAt() {
    // 1987-04-15
    long enc = 20 * 60;
    LocalDateTime date = LocalDateTime.of(1984, 1, 1, 0, 0).plusSeconds(enc * 86400);

    long S7_TIME_OFFSET = 441763200000L;
    long millis = enc * 86400000L + S7_TIME_OFFSET;
    Date date2 = new Date(millis);
    assertEquals(date.toInstant(ZoneOffset.UTC), date2.toInstant());

    LocalDateTime date3 = LocalDateTime.ofEpochSecond(millis / 1000, 0, ZoneOffset.UTC);
    assertEquals(date, date3);

    byte[] buffer = new byte[32];
    Arrays.fill(buffer, (byte) 0);
    LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(ZoneOffset.UTC), ZoneOffset.systemDefault());
    S7.setDateTimeAt(buffer, 0, ldt);

    byte[] buffer1 = new byte[32];
    Arrays.fill(buffer1, (byte) 0);
    S7.setDateAt(buffer1, 0, date2);
    Assert.assertArrayEquals(buffer, buffer1);
}
 
Example 4
Source File: ChronoZonedDateTimeImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtains an instance from an instant using the specified time-zone.
 *
 * @param chrono  the chronology, not null
 * @param instant  the instant, not null
 * @param zone  the zone identifier, not null
 * @return the zoned date-time, not null
 */
static ChronoZonedDateTimeImpl<?> ofInstant(Chronology chrono, Instant instant, ZoneId zone) {
    ZoneRules rules = zone.getRules();
    ZoneOffset offset = rules.getOffset(instant);
    Objects.requireNonNull(offset, "offset");  // protect against bad ZoneRules
    LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);
    ChronoLocalDateTimeImpl<?> cldt = (ChronoLocalDateTimeImpl<?>)chrono.localDateTime(ldt);
    return new ChronoZonedDateTimeImpl<>(cldt, offset, zone);
}
 
Example 5
Source File: TCKLocalDateTime.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void factory_ofEpochSecond_longOffset_afterEpoch() {
    LocalDateTime base = LocalDateTime.of(1970, 1, 1, 2, 0, 0, 500);
    for (int i = 0; i < 100000; i++) {
        LocalDateTime test = LocalDateTime.ofEpochSecond(i, 500, OFFSET_PTWO);
        assertEquals(test, base.plusSeconds(i));
    }
}
 
Example 6
Source File: TCKLocalDateTime.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void factory_ofEpochSecond_longOffset_beforeEpoch() {
    LocalDateTime base = LocalDateTime.of(1970, 1, 1, 2, 0, 0, 500);
    for (int i = 0; i < 100000; i++) {
        LocalDateTime test = LocalDateTime.ofEpochSecond(-i, 500, OFFSET_PTWO);
        assertEquals(test, base.minusSeconds(i));
    }
}
 
Example 7
Source File: TCKLocalDateTime.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void factory_ofEpochSecond_longOffset_afterEpoch() {
    LocalDateTime base = LocalDateTime.of(1970, 1, 1, 2, 0, 0, 500);
    for (int i = 0; i < 100000; i++) {
        LocalDateTime test = LocalDateTime.ofEpochSecond(i, 500, OFFSET_PTWO);
        assertEquals(test, base.plusSeconds(i));
    }
}
 
Example 8
Source File: TCKLocalDateTime.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void factory_ofEpochSecond_longOffset_afterEpoch() {
    LocalDateTime base = LocalDateTime.of(1970, 1, 1, 2, 0, 0, 500);
    for (int i = 0; i < 100000; i++) {
        LocalDateTime test = LocalDateTime.ofEpochSecond(i, 500, OFFSET_PTWO);
        assertEquals(test, base.plusSeconds(i));
    }
}
 
Example 9
Source File: JavatimeTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
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
Source File: TCKLocalDateTime.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofEpochSecond_longOffset_tooSmall() {
    LocalDateTime.ofEpochSecond(Long.MIN_VALUE, 500, OFFSET_PONE);  // TODO: better test
}
 
Example 11
Source File: JavatimeTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
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);
            ///////////// java.util.Date /////////////////////////
            Date jud = new java.util.Date(millis);
            Instant inst0 = jud.toInstant();
            if (jud.getTime() != inst0.toEpochMilli() ||
                !jud.equals(Date.from(inst0))) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
            }
            // roundtrip only with millis precision
            Date jud0 = Date.from(inst_ms);
            if (jud0.getTime() != inst_ms.toEpochMilli() ||
                !inst_ms.equals(jud0.toInstant())) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
            }
            //////////// java.util.GregorianCalendar /////////////
            GregorianCalendar cal = new GregorianCalendar();
            // non-roundtrip of tz name between j.u.tz and j.t.zid
            cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
            cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            cal.setMinimalDaysInFirstWeek(4);
            cal.setTimeInMillis(millis);
            ZonedDateTime zdt0 = cal.toZonedDateTime();
            if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() ||
                !cal.equals(GregorianCalendar.from(zdt0))) {
                System.out.println("cal:" + cal);
                System.out.println("zdt:" + zdt0);
                System.out.println("calNew:" + GregorianCalendar.from(zdt0));
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
            }
            inst0 = cal.toInstant();
            if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: gcal -> zdt");
            }
            ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
            GregorianCalendar cal0 = GregorianCalendar.from(zdt);
            if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() ||
                !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
            }
        }

        ///////////// java.util.TimeZone /////////////////////////
        for (String zidStr : TimeZone.getAvailableIDs()) {
            // TBD: tzdt intergration
            if (zidStr.startsWith("SystemV") ||
                zidStr.contains("Riyadh8") ||
                zidStr.equals("US/Pacific-New") ||
                zidStr.equals("EST") ||
                zidStr.equals("HST") ||
                zidStr.equals("MST")) {
                continue;
            }
            ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
            if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
                throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
            }
            TimeZone tz = TimeZone.getTimeZone(zidStr);
            // no round-trip for alias and "GMT"
            if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) &&
                !ZoneId.SHORT_IDS.containsKey(zidStr) &&
                !zidStr.startsWith("GMT")) {
                throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
            }
        }
        System.out.println("Passed!");
    }
 
Example 12
Source File: TCKLocalDateTime.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test(expected=NullPointerException.class)
public void factory_ofEpochSecond_longOffset_nullOffset() {
    LocalDateTime.ofEpochSecond(0L, 500, null);
}
 
Example 13
Source File: UnpackerImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void unpackSegment(InputStream in, JarOutputStream out) throws IOException {
    props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"0");
    // Process the output directory or jar output.
    new PackageReader(pkg, in).read();

    if (props.getBoolean("unpack.strip.debug"))    pkg.stripAttributeKind("Debug");
    if (props.getBoolean("unpack.strip.compile"))  pkg.stripAttributeKind("Compile");
    props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50");
    pkg.ensureAllClassFiles();
    // Now write out the files.
    Set<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
    for (Package.File file : pkg.getFiles()) {
        String name = file.nameString;
        JarEntry je = new JarEntry(Utils.getJarEntryName(name));
        boolean deflate;

        deflate = (keepDeflateHint)
                  ? (((file.options & Constants.FO_DEFLATE_HINT) != 0) ||
                    ((pkg.default_options & Constants.AO_DEFLATE_HINT) != 0))
                  : deflateHint;

        boolean needCRC = !deflate;  // STORE mode requires CRC

        if (needCRC)  crc.reset();
        bufOut.reset();
        if (file.isClassStub()) {
            Package.Class cls = file.getStubClass();
            assert(cls != null);
            new ClassWriter(cls, needCRC ? crcOut : bufOut).write();
            classesToWrite.remove(cls);  // for an error check
        } else {
            // collect data & maybe CRC
            file.writeTo(needCRC ? crcOut : bufOut);
        }
        je.setMethod(deflate ? JarEntry.DEFLATED : JarEntry.STORED);
        if (needCRC) {
            if (verbose > 0)
                Utils.log.info("stored size="+bufOut.size()+" and crc="+crc.getValue());

            je.setMethod(JarEntry.STORED);
            je.setSize(bufOut.size());
            je.setCrc(crc.getValue());
        }
        if (keepModtime) {
            LocalDateTime ldt = LocalDateTime
                    .ofEpochSecond(file.modtime, 0, ZoneOffset.UTC);
            je.setTimeLocal(ldt);
        } else {
            je.setTime((long)modtime * 1000);
        }
        out.putNextEntry(je);
        bufOut.writeTo(out);
        out.closeEntry();
        if (verbose > 0)
            Utils.log.info("Writing "+Utils.zeString((ZipEntry)je));
    }
    assert(classesToWrite.isEmpty());
    props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"100");
    pkg.reset();  // reset for the next segment, if any
}
 
Example 14
Source File: TCKLocalDateTime.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofEpochSecond_longOffset_tooSmall() {
    LocalDateTime.ofEpochSecond(Long.MIN_VALUE, 500, OFFSET_PONE);  // TODO: better test
}
 
Example 15
Source File: TCKLocalDateTime.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofEpochSecond_longOffset_tooBig() {
    LocalDateTime.ofEpochSecond(Long.MAX_VALUE, 500, OFFSET_PONE);  // TODO: better test
}
 
Example 16
Source File: TCKLocalDateTime.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofEpochSecond_badNanos_toSmall() {
    LocalDateTime.ofEpochSecond(0, -1, OFFSET_PONE);
}
 
Example 17
Source File: DateUtil.java    From notes with Apache License 2.0 4 votes vote down vote up
public static LocalDateTime timeToLocalDateTime(Long time){
    LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(time / 1000, 0, ZoneOffset.ofHours(8));
    return localDateTime;
}
 
Example 18
Source File: UseLocalDateTime.java    From tutorials with MIT License 4 votes vote down vote up
LocalDateTime ofEpochSecond(int epochSecond, ZoneOffset zoneOffset) {
    return LocalDateTime.ofEpochSecond(epochSecond, 0, zoneOffset);
}
 
Example 19
Source File: ZoneOffsetTransition.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an instance from epoch-second and offsets.
 *
 * @param epochSecond  the transition epoch-second
 * @param offsetBefore  the offset before the transition, not null
 * @param offsetAfter  the offset at and after the transition, not null
 */
ZoneOffsetTransition(long epochSecond, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
    this.epochSecond = epochSecond;
    this.transition = LocalDateTime.ofEpochSecond(epochSecond, 0, offsetBefore);
    this.offsetBefore = offsetBefore;
    this.offsetAfter = offsetAfter;
}
 
Example 20
Source File: ZoneOffsetTransition.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Creates an instance from epoch-second and offsets.
 *
 * @param epochSecond  the transition epoch-second
 * @param offsetBefore  the offset before the transition, not null
 * @param offsetAfter  the offset at and after the transition, not null
 */
ZoneOffsetTransition(long epochSecond, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
    this.epochSecond = epochSecond;
    this.transition = LocalDateTime.ofEpochSecond(epochSecond, 0, offsetBefore);
    this.offsetBefore = offsetBefore;
    this.offsetAfter = offsetAfter;
}