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 @ 2019-04-02 12:03  刘百会  阅读(29194)  评论(0编辑  收藏  举报