前言

Github:https://github.com/HealerJean

博客:http://blog.healerjean.com

LocalTime : 只包括时间

LocalDate : 只包括日期

LocalDateTime : 包括日期和时间


**mapper中JDBC映射 **

LocalTime 对应 time

LocalDate 对应 date

LocalDateTime 对应 timestamp

1、LocalTime

1.1、构造

//LocalTime包含毫秒
LocalTime now = LocalTime.now(); // 11:09:09.240
//清除毫秒数
LocalTime now = LocalTime.now().withNano(0)); // 11:09:09


LocalTime localtime = LocalTime.of(0, 0, 0); // 00:00:00

字符串截取严格按照ISO yyyy-MM-dd验证
LocalTime localtime = LocalTime.parse("12:00:00"); // 12:00:00

2、LocalDate

2.1、构造

LocalDate today = LocalDate.now(); 

LocalDate date = LocalDate.of(2017, 5, 25); 
LocalDate date = LocalDate.of(2017, 05, 25); 

字符串截取严格按照ISO yyyy-MM-dd验证
LocalDate date = LocalDate.parse("2014-02-28"); //正确
LocalDate date = LocalDate.parse("2014-2-28"); //错误
LocalDate date = LocalDate.parse("2014-02-29"); // 无效日期无法通过:

3、LocalDateTime

3.1、构造


LocalDateTime d1 = LocalDateTime.of(2013, 12, 31, 23, 59);    //年,月,日,时,分
输出;2013-12-31T23:59

    LocalDateTime d3 = LocalDateTime.of(2013, 12, 31, 23, 59,59); //年,月,日,时,分,秒
输出;2013-12-31T23:59:59
    LocalDateTime d2 = LocalDateTime.of(2013, 12, 31, 23, 59,59, 11);  //年,月,日,时,分,秒毫秒
输出2013-12-31T23:59:59.000000011




    LocalDateTime d1 = LocalDateTime.parse("2013-12-31T23:59");
LocalDateTime d2 = LocalDateTime.parse("2013-12-31T23:59:59");
LocalDateTime d3 = LocalDateTime.parse("2013-12-31T23:59:59.000000011");    

4、标准格式yyyyMMdd 的字符串转化


public static final String YYYYMMdd = "yyyyMMdd";
public static final String YYYY_MM_dd = "yyyy-MM-dd";
public static final String YYYY_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";


public static LocalDate toLocalDate(String dateStr, String format){
    DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
    LocalDate parse = LocalDate.parse(dateStr , df);
    return  parse;
}

public static String toDateString(LocalDate localDate, String format){
    DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
    return df.format(localDate);
}

public static LocalDateTime toLocalDateTime(String dateStr, String format){
    DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
    LocalDateTime parse = LocalDateTime.parse(dateStr , df);
    return  parse;
}

public static String  toDateString(LocalDateTime localDateTime, String format){
    DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
    return  localDateTime.format(df);
    //下面这个也可以
    // return df.format(localDateTime);
}



public static LocalDateTime toLocalDateTimeByMills(Long timestamp){
    ZoneId zoneId = ZoneId.systemDefault() ;
    Instant instant = Instant.ofEpochMilli(timestamp);
    return  instant.atZone(zoneId).toLocalDateTime();
}

public static Long toTimeInMills(LocalDateTime localDateTime){
    ZoneId zoneId = ZoneId.systemDefault() ;
    Instant instant = localDateTime.atZone(zoneId).toInstant();
    return instant.toEpochMilli() ;
}

public static Long toTimeInSecond (LocalDateTime localDateTime){
    ZoneId zoneId = ZoneId.systemDefault() ;
    Instant instant = localDateTime.atZone(zoneId).toInstant();
    return instant.getEpochSecond() ;
}

5、Date和LocalDate之间的转化

public static Date toDate(LocalDateTime localDateTime){
    ZoneId zoneId = ZoneId.systemDefault() ;
    Instant instant = localDateTime.atZone(zoneId).toInstant();
    return  Date.from(instant);
}

public static LocalDateTime toLocalDateTime(Date date){
    ZoneId zoneId = ZoneId.systemDefault() ;
    Instant instant = date.toInstant();
    return instant.atZone(zoneId).toLocalDateTime();
}

public static Date toDate(LocalDate localDate){
    ZoneId zoneId = ZoneId.systemDefault() ;
    Instant instant = localDate.atStartOfDay(zoneId).toInstant();
    return  Date.from(instant);
}
public static LocalDate toLocalDate(Date date){
    ZoneId zoneId = ZoneId.systemDefault() ;
    Instant instant = date.toInstant();
    return instant.atZone(zoneId).toLocalDate();
}

6、一些常用方法介绍

6.1、获取固定的日期

LocalDate.now().getYear(); // 年份  
LocalDate.now().getMonthValue(); // 月份(数值表示, 从1开始)  
LocalDate.now().getMonth(); // 月份(英文[enum]表示)  
LocalDate.now().getDayOfMonth(); // 日期(从1开始)  
LocalDate.now().getDayOfYear(): // 当天所在这一年的第几天(从1开始)  
LocalDate.now().getDayOfWeek(); // 星期几  
LocalDate.now().lengthOfYear(); // 当年的天数  
LocalDate.now().lengthOfMonth(); //当月的天数  
LocalDate.now().toEpochDay(); // 与时间纪元(1970年1月1日)相差的天数,负数表示在时间纪元之前多少天  

6.2、加减法

System.out.println("加法运算");  
System.out.println("当前:" + LocalDate.now());  
System.out.println("加1天:" + LocalDate.now().plusDays(1));  
System.out.println("加1周:" + LocalDate.now().plusWeeks(1));  
System.out.println("加1月:" + LocalDate.now().plusMonths(1));  
System.out.println("加1年:" + LocalDate.now().plusYears(1));  


System.out.println("减法运算");  
System.out.println("当前:" + LocalDate.now());  
System.out.println("减1天:" + LocalDate.now().minusDays(1));  
System.out.println("减1周:" + LocalDate.now().minusWeeks(1));  
System.out.println("减1月:" + LocalDate.now().minusMonths(1));  
System.out.println("减1年:" + LocalDate.now().minusYears(1));  


LocalDate nextWeek  = today.plus(1, ChronoUnit.WEEKS); //加一周
LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);//加一月
LocalDate nextDecade = today.plus(1, ChronoUnit.DECADES); //加10年

6.3、替换(可以搭配使用)

所有的数值必须合法
如果当月当天是闰年2月29日替换年份为非闰年则会变成2月28日

System.out.println("当前:" + LocalDate.now());  
System.out.println("替换日期为1:" + LocalDate.now().withDayOfMonth(1));  
System.out.println("替换天数为1:" + LocalDate.now().withDayOfYear(1));  
System.out.println("替换月份为1:" + LocalDate.now().withMonth(1));  
System.out.println("替换年份为1:" + LocalDate.now().withYear(1));

当前2019-07-17
替换日期为12019-07-01
替换天数为12019-01-01
替换月份为12019-01-17
替换年份为10001-07-17

6.4、判断

可以对两个 LocalDate 进行比较可以判断一个日期是否在另一个日期之前或之后或者判断两个日期是否是同年同月同日

System.out.println("当天:" + LocalDate.now());  
System.out.println("是否在当天之前:" + LocalDate.now().minusDays(1).isBefore(LocalDate.now()));  
System.out.println("是否在当天之后:" + LocalDate.now().plusDays(1).isAfter(LocalDate.now()));  
System.out.println("是否在当天:" + LocalDate.now().isEqual(LocalDate.now()));  
System.out.println("今年是否是闰年:" + LocalDate.now().isLeapYear());  
	
	
当天2019-07-17
是否在当天之前true
是否在当天之后true
是否在当天true
今年是否是闰年false

6.5、计算

6.5.1、 计算两个时间相差多少天、月 建议使用ChronoUnit 更全面一些
LocalDateTime startTime = LocalDateTime.now();
LocalDateTime endTime = startTime.plusDays(7);

//这里的参数只能是LocalDate
int daysNum = Period.between(startTime.toLocalDate(), endTime.toLocalDate()).getDays();
int monthNum = Period.between(startTime.toLocalDate(), endTime.toLocalDate()).getMonths();
System.out.println("相差天数:" + daysNum);
System.out.println("相差月数:" + monthNum);

long  daysDiff  = ChronoUnit.DAYS.between(startTime, endTime);
long  monthDiff = ChronoUnit.MONTHS.between(startTime, endTime);
long  hourDiff  = ChronoUnit.HOURS.between(startTime, endTime);

System.out.println("相差天数:" + daysDiff);
System.out.println("相差月数:" + monthDiff);
System.out.println("相差小时:" + hourDiff);

6、Contorller中使用

4.1、Local类型的日期

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
    });
    binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
    });
    binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss")));
        }
    });
}

4.2、普通date


@InitBinder
public void dateBinder(WebDataBinder binder){
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
}

4.3、全局配置(不一定好使,小爷的就不好使,最后用了第一种)

@Configuration
public class DateConfig {
    /***
     * 日期参数接收转换器,将json字符串转为日期类型
     * @return
     */
    @Bean
    public Converter<String, LocalDateTime> LocalDateTimeConvert() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public JavaType getInputType(TypeFactory typeFactory) {
                return null;
            }

            @Override
            public JavaType getOutputType(TypeFactory typeFactory) {
                return null;
            }

            @Override
            public LocalDateTime convert(String source) {

                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime date = null;
                try {
                    date = LocalDateTime.parse((String) source,df);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return date;
            }
        };
    }

    /***
     * 日期参数接收转换器,将json字符串转为日期类型
     * @return
     */
    @Bean
    public Converter<String, LocalDate> LocalDateConvert() {
        return new Converter<String, LocalDate>() {
            @Override
            public JavaType getInputType(TypeFactory typeFactory) {
                return null;
            }

            @Override
            public JavaType getOutputType(TypeFactory typeFactory) {
                return null;
            }

            @Override
            public LocalDate convert(String source) {

                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate date = null;
                try {
                    date = LocalDate.parse((String) source,df);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return date;
            }
        };
    }
}

7、JsonUtils讲它转化成字符串


static {

    OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);

    //NULL 不打印
    OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    //LocalDateTime   LocalDate LocalTime 转化成 String
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

    OBJECT_MAPPER.registerModule(javaTimeModule);
    OBJECT_MAPPER.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

8、LocalDate工具类

public class LocalDateUtils {

    public static final String YYYYMMdd = "yyyyMMdd";
    public static final String YYYY_MM_dd = "yyyy-MM-dd";
    public static final String YYYY_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";


    public static LocalDate toLocalDate(String dateStr, String format){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        LocalDate parse = LocalDate.parse(dateStr , df);
        return  parse;
    }

    public static String toDateString(LocalDate localDate, String format){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return df.format(localDate);
    }

    public static LocalDateTime toLocalDateTime(String dateStr, String format){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        LocalDateTime parse = LocalDateTime.parse(dateStr , df);
        return  parse;
    }
    public static String  toDateString(LocalDateTime localDateTime, String format){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return  localDateTime.format(df);
        //下面这个也可以
        // return df.format(localDateTime);
    }

    public static LocalDateTime localDateToLocalDateTime (LocalDate localDate){
        String dateStr = LocalDateUtils.toDateString(localDate, LocalDateUtils.YYYY_MM_dd);
        LocalDateTime localDateTime = LocalDateUtils.toLocalDateTime(dateStr+" 00:00:00", LocalDateUtils.YYYY_MM_dd_HH_mm_ss);
        return localDateTime ;
    }



    public static Date toDate(LocalDateTime localDateTime){
        ZoneId zoneId = ZoneId.systemDefault() ;
        Instant instant = localDateTime.atZone(zoneId).toInstant();
        return  Date.from(instant);
    }

    public static LocalDateTime toLocalDateTime(Date date){
        ZoneId zoneId = ZoneId.systemDefault() ;
        Instant instant = date.toInstant();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    public static Date toDate(LocalDate localDate){
        ZoneId zoneId = ZoneId.systemDefault() ;
        Instant instant = localDate.atStartOfDay(zoneId).toInstant();
        return  Date.from(instant);
    }
    public static LocalDate toLocalDate(Date date){
        ZoneId zoneId = ZoneId.systemDefault() ;
        Instant instant = date.toInstant();
        return instant.atZone(zoneId).toLocalDate();
    }


    public static LocalDateTime toLocalDateTimeByMills(Long timestamp){
        ZoneId zoneId = ZoneId.systemDefault() ;
        Instant instant = Instant.ofEpochMilli(timestamp);
        return  instant.atZone(zoneId).toLocalDateTime();
    }

    public static Long toTimeInMills(LocalDateTime localDateTime){
        ZoneId zoneId = ZoneId.systemDefault() ;
        Instant instant = localDateTime.atZone(zoneId).toInstant();
        return instant.toEpochMilli() ;
    }

    public static Long toTimeInSecond (LocalDateTime localDateTime){
        ZoneId zoneId = ZoneId.systemDefault() ;
        Instant instant = localDateTime.atZone(zoneId).toInstant();
        return instant.getEpochSecond() ;
    }

}

ContactAuthor