【Java】时间戳与秒、毫秒转化

1、时间戳转换成秒

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;            //导入三个需要的包

        //日期字符串转LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse("2020-12-07 10:56:15.002", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));

        //LocalDateTime转时间秒数
        long seconds = localDateTime.atZone(ZoneId.systemDefault()).toEpochSecond();
        System.out.println(seconds);

2、时间戳转换成毫秒

//日期字符串转LocalDateTime
LocalDateTime localDateTime = LocalDateTime.parse("2020-12-07 14:53:03.785", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))

//这里LocalDateTime必须要先转成Instant,之后才能获取对应的时间毫秒数
long millis = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

3、毫秒,秒转化成时间

//通过时间毫秒数创建Instant实例
Instant instant = Instant.ofEpochMilli(1507309800001L); //2017-10-06T17:10:00.001Z

//通过系统默认时区创建ZonedDateTime
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault()); //2017-10-07T01:10:00.001+08:00[Asia/Shanghai]

//从ZonedDateTime中获取LocalDateTime部分
LocalDateTime localDateTime = zonedDateTime.toLocalDateTime(); //2017-10-07T01:10:00.001

//格式化LocalDateTime
String time = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); //2017-10-07 01:10:00

你可能感兴趣的:(Java,java)