Java jdk1.8 LocalDateTime 时间戳转换

LocalDateTime和时间戳互转

  /**
     * 获取到毫秒级时间戳
     * @param localDateTime 具体时间
     * @return long 毫秒级时间戳
     */
    public static long toEpochMilli(LocalDateTime localDateTime){
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 毫秒级时间戳转 LocalDateTime
     * @param epochMilli 毫秒级时间戳
     * @return LocalDateTime
     */
    public static LocalDateTime ofEpochMilli(long epochMilli){
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneOffset.of("+8"));
    }

    /**
     * 获取到秒级时间戳
     * @param localDateTime 具体时间
     * @return long 秒级时间戳
     */
    public static long toEpochSecond(LocalDateTime localDateTime){
        return localDateTime.toEpochSecond(ZoneOffset.of("+8"));
    }

    /**
     * 秒级时间戳转 LocalDateTime
     * @param epochSecond 秒级时间戳
     * @return LocalDateTime
     */
    public static LocalDateTime ofEpochSecond(long epochSecond){
        return LocalDateTime.ofEpochSecond(epochSecond, 0,ZoneOffset.of("+8"));
    }

LocalDateTime和Date互转

    /**
     * Date时间类转LocalDateTime
     * @param date Date时间类
     * @return LocalDateTime
     */
    public static LocalDateTime ofDate(Date date){
        return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
    }

    /**
     * LocalDateTime时间类转 Date时间类
     * @param localDateTime LocalDateTime时间类
     * @return Date时间类
     */
    public static Date toDate(LocalDateTime localDateTime){
        return Date.from(localDateTime.atZone(ZoneOffset.of("+8")).toInstant());
    }

LocalDateTime和字符串互转

    /**
     * LocalDateTime转时间格式字符串
     * @param localDateTime 时间
     * @return string 
     */
    public static String formatToString(LocalDateTime localDateTime){
        String format  = "yyyy:MM:dd HH:mm:ss";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        return localDateTime.format(dateTimeFormatter);
    }

    /**
     *  时间字符串 转LocalDateTime
     * @param localDateTime  时间字符串
     * @return LocalDateTime
     */
    public static LocalDateTime stringToFormat(String localDateTime){
        String format  = "yyyy:MM:dd HH:mm:ss";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(localDateTime,dateTimeFormatter);
    }

 

posted @ 2021-03-23 13:55  陈彦斌  阅读(9633)  评论(0编辑  收藏  举报