Spring-Boot-18-时间转换

本文介绍了一个名为TimeUtil的组件,它提供了将Long类型的Timestamp转换为LocalDateTime,并支持各种日期格式化的方法,包括默认日期、毫秒级转换和区域化展示。此外,还包括获取本周一的功能。

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

  1. 主要涉及到LocalDateTime和TimeStamp之间的转换
@Component
public class TimeUtil {
    public static LocalDateTime getLocalDateTime(long timestamp){
        LocalDateTime time = LocalDateTime.ofEpochSecond(timestamp/1000,0, ZoneOffset.ofHours(0));
        return time;
    }

    public static LocalDateTime getDefaultLocalDateTime(){
        LocalDateTime time = LocalDateTime.ofEpochSecond(946656000/1000,0,ZoneOffset.ofHours(0));
        return time;
    }

    //毫秒为单位
    public static long getTimeStamp(LocalDateTime localDateTime){
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    public static String dateToString(LocalDateTime localDateTime){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateTime = localDateTime.format(formatter);
        return dateTime;
    }

    public static String dateToAreaString(LocalDateTime localDateTime){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM月dd日 HH:mm");
        String dateTime = localDateTime.format(formatter);
        return dateTime;
    }

    public static String dateToVOString(LocalDateTime localDateTime){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String dateTime = localDateTime.format(formatter);
        return dateTime;
    }

    public static String preTime(){
        return dateToVOString(LocalDateTime.now()) + " ";
    }

    public static LocalDateTime toDay(LocalDateTime input){
        String time = dateToString(input);
        String[] temp = time.split("-");
        return LocalDateTime.of(Integer.valueOf(temp[0]),Integer.valueOf(temp[1]), Integer.valueOf(temp[2]),0,0);
    }

    /**
     * 获取本周一
     * @return
     */
    public static LocalDateTime weekFirstDay(){
        LocalDateTime localDateTime = LocalDateTime.now();
        int days_of_week = localDateTime.getDayOfWeek().getValue();
        localDateTime = localDateTime.minusDays(days_of_week - 1);
        return toDay(localDateTime);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值