当前位置: 首页 > 工具软件 > jav8 > 使用案例 >

Jav8不能错过的时间操作

陶刚豪
2023-12-01

java8之前的时间操作都过于复杂,java8之后推出了一个新的时间类,方便了时间上的操作。下面我们来解析一个基于java8新的时间类的各种操作方式

将时间格式转为对应的LocalDateTime

String openTimeStr = "2021-03-09 10:00:00";
LocalDateTime serverOpenDate = LocalDateTime.parse(openTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

将LocalDateTime 转为 LocalDate

LocalDate serverOpen = serverOpenDate.toInstant(ZoneOffset.ofHours(8)).atZone(ZoneOffset.ofHours(8)).toLocalDate();

LocalDate转为时间戳

LocalDateTime now = LocalDateTime.now();
long nowTime = now.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

LocalDateTime转时间戳

LocalDateTime localDateTime = LocalDateTime.now();
longtimestamp = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

获取两个LocalDate相隔的天数

int days = (int)(now1.toEpochDay()-serverOpen.toEpochDay());

将时间戳转为对应格式的字符串

long time = System.currentTimeMillis(); //"时间戳(且单位为毫秒)"
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault()));

时间戳与localdate、localdatetime转换

long timestamp = System.currentTimeMillis();
// oneOffset.ofHours(8) 获取那个时区
LocalDate localDate = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDate();
System.out.println(localDate);
LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
System.out.println(localDateTime);

LocalDate转Date

LocalDate nowLocalDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());

LocalDateTime转Date

LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant());

Date转LocalDateTime(LocalDate)

Date date =new Date();
LocalDateTime localDateTime = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
LocalDate localDate = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDate();

获取指定时间的0点和24点的时间

    // 获得某天最大时间 
    public static Date getEndOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());;
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }
 
    // 获得某天最小时间
    public static Date getStartOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
        return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }
 类似资料: