java8 LocalDateTime时间格式化

 LocalDateTime time = techLogicTablePo.getCreateTime();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String createTime = dateTimeFormatter.format(time);

 

java 关于时间返回结果与参数的注解@DatetimeFormat和@JsonFormat

时间是一个比较常用的类型。显示的时候通常是以String显示的。如果前端参数,前端人员也希望用String作为参数

常用注解

@DatetimeFormat是将String转换成Date,一般前台给后台传值时用


@JsonFormat(pattern="yyyy-MM-dd") 将Date转换成String 一般后台传值给前台时

@JsonFormat会让时间以0区时间显示。如果直接使用会少了8小时(我所在的是北京时区)修改为

@JsonFormat(pattern="yyyy-MM-dd",timezone="GMT+8")

 

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")

现在时间到过去7天时间

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String nowTime = dateTimeFormatter.format(now);
LocalDateTime localDateTime = now.minusDays(7);
String startTime = dateTimeFormatter.format(localDateTime);

localdatetime获取当天0点

复制代码
public class Test {

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间:  "+now);
        
        //时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("formate: "+ now.format(formatter));
        
        //当天的零点
        System.out.println("当天的零点:  "+LocalDateTime.of(now.toLocalDate(), LocalTime.MIN));
        
        //当天的最后时间
        System.out.println("当天的最后时间:  "+LocalDateTime.of(now.toLocalDate(), LocalTime.MAX));
        
        //最近的五分钟点位
        Integer minute = now.getMinute();
        minute = minute/5*5;
        System.out.println("最近的五分钟点位:  "+LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), now.getHour(), minute, 0));
        
        //Date转为LocalDateTime
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println("Date转为LocalDateTime: "+instant.atZone(zoneId).toLocalDateTime());
    }

}
复制代码

 

posted @   刘百会  阅读(29234)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示