当前位置: 首页 > 图灵资讯 > 技术篇> Java8 LocalDateTime获取时间戳(毫秒、秒)、LocalDateTime与String互转、Date与LocalDateTime互转

Java8 LocalDateTime获取时间戳(毫秒、秒)、LocalDateTime与String互转、Date与LocalDateTime互转

来源:图灵教育
时间:2023-06-11 09:17:15

1.Localdatetime获得毫秒数/获得秒数Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of(+8);//获得毫秒数Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of(+8).toEpochMilli();  2.Localdatetime与String互转/时间转字符串格式化 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"); String dateTime = LocalDateTime.now(ZoneOffset.of(+8).format(formatter); ///字符串转时间String dateTimeStr = "2018-07-28 14:11:15";DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, df); 3.Date与LocalDatetime互转    //将java.util.Date 转换为java8 的java.time.LocalDateTime,东8区是默认时区    public static LocalDateTime dateConvertToLocalDateTime(Date date) {        return date.toInstant().atOffset(ZoneOffset.of(+8).toLocalDateTime();    }        //将java8 的 java.time.LocalDateTime 转换为 java.util.Date,东8区是默认时区    public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {        return Date.from(localDateTime.toInstant(ZoneOffset.of(+8);    }      /**     * 测试转换是否正确     */    @Test    public void testDateConvertToLocalDateTime() {        Date date = DateUtils.parseDate("2018-08-01 21:22:22", DateUtils.DATE_YMDHMS);        LocalDateTime localDateTime = DateUtils.dateConvertToLocalDateTime(date);        Long localDateTimeSecond = localDateTime.toEpochSecond(ZoneOffset.of(+8);        Long dateSecond = date.toInstant().atOffset(ZoneOffset.of(+8).toEpochSecond();        Assert.assertTrue(dateSecond.equals(localDateTimeSecond));    }