Java8新增时间类LocalDateTime、LocalDate、LocalTime,以及在Spring中作为参数入参

  • Post author:
  • Post category:java




Java8新增时间类LocalDateTime、LocalDate、LocalTime,以及在Spring中作为参数入参



线程安全


以前我们习惯用的Date时间类是可变类,在多线程环境下操作时需要保证线程安全、而LocalDateTime、LocalDate、LocalTime类是不可变类,并且是线程安全的。


在日期格式化选择上Date使用的SimpleDateFormat本身也是线程不安全的,而现在取而代之的是DateTimeFormatter类,是线程安全的。



查看源码比较


LocalDateTime


LocalDateTime


DateTimeFormatter


DateTimeFormatter


SimpleDateFormat


SimpleDateFormat



LocalDateTime、LocalDate、LocalTime使用



获取当前时刻
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("表示当前时间:"+localDateTime);
        System.out.println("表示当前年份:"+localDateTime.getYear());
        System.out.println("表示当前月份:"+localDateTime.getMonth());
        System.out.println("表示当前月份:"+localDateTime.getMonthValue());
        System.out.println("表示当天日期:"+localDateTime.getDayOfMonth());
        System.out.println("表示当前时:"+localDateTime.getHour());
        System.out.println("表示当前分:"+localDateTime.getMinute());
        System.out.println("表示当前秒:"+localDateTime.getSecond());
        System.out.println("表示当前星期几:"+localDateTime.getDayOfWeek());
        System.out.println("表示当前是一年中的第几天:"+localDateTime.getDayOfYear());
        System.out.println("表示当前纳秒数:"+localDateTime.getNano());


LocalDate、LocalTime方法同上



构造时间:指定年月日时分秒

        LocalDateTime dateTime = LocalDateTime.of(2020, 2, 15, 06, 25, 45);
        LocalDateTime dateTime1 = LocalDateTime.of(2020, Month.FEBRUARY, 15, 06, 25, 45);
        System.out.println("构造日期2020-02-15 06:25:45"+dateTime);
        System.out.println("构造日期2020-02-15 06:25:45"+dateTime1);



修改日期

        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println("减少两年"+dateTime.minusYears(2));
        System.out.println("减少两天"+dateTime.minusDays(2));
        System.out.println("增加两年"+dateTime.plusYears(2));
        System.out.println("增加两天"+dateTime.plusDays(2));
        System.out.println("修改年份到2019"+dateTime.withYear(2019));
        System.out.println("修改月份到3月"+dateTime.withMonth(3));



日期格式化

        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println("格式化日期"+dateTime.format(DateTimeFormatter.ISO_DATE));
        System.out.println("格式化日期"+dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
        System.out.println("格式化日期"+dateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));


输出结果

格式化日期2020-02-15
格式化日期20200215
格式化日期2020/02/15



时间反解析

        LocalDateTime parse = LocalDateTime.parse("2020-02-15 06:42:34", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("时间反解析"+parse);



时间计算

        LocalDate localDate = LocalDate.now();
        System.out.println("本月第一天"+localDate.with(TemporalAdjusters.firstDayOfMonth()));
        System.out.println("本月最后一天"+localDate.with(TemporalAdjusters.lastDayOfMonth()));
        System.out.println("取2020年1月第一个周一"+LocalDate.parse("2020-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));



其他常用方法

        LocalDateTime dateTime1 = LocalDateTime.of(2020, 2, 15, 06, 25, 45);
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println("判断LocalDateTime是否在指定LocalDateTime之后"+dateTime1.isAfter(dateTime));
        System.out.println("时间反解析判断LocalDateTime是否在指定LocalDateTime之前"+dateTime1.isBefore(dateTime));
        System.out.println("判断LocalDateTime是否在指定LocalDateTime相等"+dateTime1.isEqual(dateTime));
        System.out.println("返回LocalDateTime的LocalDate部分"+dateTime.toLocalDate());
        System.out.println("返回LocalDateTime的LocalTime部分"+dateTime.toLocalTime());
        System.out.println("返回LocalDateTime的字符串表示 "+dateTime.toString());



当LocalDateTime、LocalDate、LocalTime作为RequestParam或者PathVariable时,使用Converter转换,如果以Json形式传入时,使用Jackson的json序列化和反序列化来转换。

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author yly
 * @ClassName DateConfig
 * @Date 2020/2/15 7:59
 * @Version 1.0
 **/
@Configuration
public class DateConfig  {

    /**
     * 默认日期时间格式
     */
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /** 
     * 默认日期格式 
     */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    /** 
     * 默认时间格式 
     */
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    /**
     * LocalDate转换器,用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
            }
        };
    }

    /**
     * LocalDateTime转换器,用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
            }
        };
    }

    /**
     * LocalTime转换器,用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, LocalTime> localTimeConverter() {
        return new Converter<String, LocalTime>() {
            @Override
            public LocalTime convert(String source) {
                return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
            }
        };
    }

    /**
     * Date转换器,用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, Date> dateConverter() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
                try {
                    return format.parse(source);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }


    /**
     * Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
     */
    @Bean
    public ObjectMapper objectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

        //LocalDateTime系列序列化和反序列化模块,继承自jsr310,我们在这里修改了日期格式
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));


        //Date序列化和反序列化
        javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
            @Override
            public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
                String formattedDate = formatter.format(date);
                jsonGenerator.writeString(formattedDate);
            }
        });
        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
                String date = jsonParser.getText();
                try {
                    return format.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
            @Override
            public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
                String formattedDate = formatter.format(date);
                jsonGenerator.writeString(formattedDate);
            }
        });
        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
                String date = jsonParser.getText();
                try {
                    return format.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

}



创建DateModel

/**
 * @author yly
 * @ClassName DateModel
 * @Date 2020/2/15 8:06
 * @Version 1.0
 **/

public class DateModel {
    private Date date;
    private LocalDateTime localDateTime;
    private LocalDate localDate;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public LocalDateTime getLocalDateTime() {
        return localDateTime;
    }

    public void setLocalDateTime(LocalDateTime localDateTime) {
        this.localDateTime = localDateTime;
    }

    public LocalDate getLocalDate() {
        return localDate;
    }

    public void setLocalDate(LocalDate localDate) {
        this.localDate = localDate;
    }
}



创建controller

@RestController
public class DateController {
    @RequestMapping("/requestParamDateMOdel")
   public DateModel dateModel(DateModel dateModel){
        return dateModel;
   }

    @RequestMapping("/requestBodyDateMOdel")
    public DateModel getDateModel(@RequestBody DateModel dateModel){
        return dateModel;
    }
}



请求

在这里插入图片描述

在这里插入图片描述



对应的SQL类型

SQL -> Java
date -> LocalDate
time -> LocalTime
timestamp -> LocalDateTime



版权声明:本文为qq_43813937原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。