JAVA中时间戳和LocalDateTime的互转
时间戳转LocalDateTime:
要将时间戳转换为LocalDateTime并将LocalDateTime转换回时间戳,使用Java的java.time包。以下是示例代码:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class TimestampToLocalDateTime {
    public static void main(String[] args) {
    	// 注意:这里是秒级时间戳
        long timestamp = 1692948472; 
        // 使用Instant从时间戳创建时间点
        Instant instant = Instant.ofEpochSecond(timestamp);
        // 使用ZoneId定义时区(可以根据需要选择不同的时区)
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        // 将Instant转换为LocalDateTime
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        System.out.println("时间戳: " + timestamp);
        System.out.println("转换后的LocalDateTime: " + localDateTime);
    }
}
LocalDateTime转时间戳:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class LocalDateTimeToTimestamp {
    public static void main(String[] args) {
        // 创建一个LocalDateTime对象
        LocalDateTime localDateTime = LocalDateTime.of(2023, 8, 25, 0, 0);
        // 使用ZoneId定义时区(可以根据需要选择不同的时区)
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        // 将LocalDateTime转换为Instant
        Instant instant = localDateTime.atZone(zoneId).toInstant();
        // 获取时间戳
        long timestamp = instant.getEpochSecond();
        System.out.println("LocalDateTime: " + localDateTime);
        System.out.println("转换后的时间戳: " + timestamp);
    }
}