Java8中LocalDateTime与时间戳timestamp的互相转换及ChronoUnit工具类

2024-10-09 10:04:58 浏览数 (4)

Java8中LocalDateTime与时间戳timestamp的互相转换及ChronoUnit工具类import java.time.*;import java.time.format.DateTimeFormatter;

代码语言:javascript复制
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;

/**
 * Java8中LocalDateTime与时间戳timestamp的互相转换
 */
public class DateUtils {

    /**
     *
     * @param timestamp
     * @return
     */
    public static LocalDateTime timestamToDatetime(long timestamp){
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    /**
     *获取指定日期的毫秒
     * @param ldt
     * @return
     */
    public static long datatimeToTimestamp(LocalDateTime ldt){
//        long timestamp = ldt.toInstant(ZoneOffset.of(" 8")).toEpochMilli();
//        return timestamp;
        ZoneId zone = ZoneId.systemDefault();
        long timestamp = ldt.atZone(zone).toInstant().toEpochMilli();
        return timestamp;
    }
  

0 人点赞