LocalTimeUtil 时间转换 工具类

这是一个Java时间处理工具类,包含获取某天最大和最小时间戳的方法,以及转换为LocalDateTime的辅助函数。例如,可以用来获取某一天的开始和结束时间(如2020-02-19 00:00:00和2020-02-19 23:59:59)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.jsy.basic.util;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class LocalTimeUtil {

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //  获得某天最大时间戳 2020-02-19 23:59:59
    public static long getEndOfDay(LocalDateTime date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.toInstant(ZoneOffset.of("+8")).toEpochMilli()), ZoneId.systemDefault());
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant()).getTime();
    }
    //  获得某天最小时间戳 2020-02-17 00:00:00
    public static long getStartOfDay(LocalDateTime date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.toInstant(ZoneOffset.of("+8")).toEpochMilli()), ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
        return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()).getTime();
    }


    //  LocalDateTime 2021-2-21T00:00:00
    public static LocalDateTime getStart(int i){
        LocalDate today = LocalDate.now();
        LocalDate localDate = today.minusDays(i);
        long timestamp = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
        LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
        return localDateTime;
    }
    //  LocalDateTime 2021-2-21T23:59:59
    public static LocalDateTime getEnd(int i){
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime endOfDay = localDateTime.minusDays(i).with(LocalTime.MAX);
        return endOfDay;
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值