LocalDate 简介

LocalDate  是Java 8 推出了全新的日期时间API,在类中明确了日期时间概念,同时继承了Joda 库按人类语言和计算机各自解析的时间处理方式。不同于老版本,新API基于ISO标准日历系统,java.time包下的所有类都是不可变类型而且线程安全。(以前 java.util.Date 为可变类型,SimpleDateFormat 等非线程安全)

LocalDate 关键类

  • Instant:瞬时实例。
  • LocalDate:本地日期,不包含具体时间 例如:2014-01-14 可以用来记录生日、纪念日、加盟日等。
  • LocalTime:本地时间,不包含日期。
  • LocalDateTime:组合了日期和时间,但不包含时差和时区信息。
  • ZonedDateTime:最完整的日期时间,包含时区和相对UTC或格林威治的时差。
  • ZoneOffSet 和 ZoneId:使得解决时区问题更为简便。
  • DateTimeFormatter:解析、格式化时间。

一份Demo

package com.ycdhz.common.utils;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;

public class DateUtil {

    public static LocalDate date2LocalDate(Date date) {
        if(null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    public static Date localDate2Date(LocalDate localDate) {
        if(null == localDate) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

    /**
     * 获取当前日期yyyy-MM-dd
     * @return
     */
    public static LocalDate getCurrentDay(){
        LocalDate localDate = LocalDate.now();
        System.out.println(String.format("%s年%s月%s日",
                localDate.getYear(),
                localDate.getMonthValue(),
                localDate.getDayOfMonth()));
        return LocalDate.now();
    }

    /**
     * 获取当前时间
     * @return
     */
    public static LocalDateTime getCurrentTime(){
        return LocalDateTime.now();
    }

    /**
     * 处理特定日期
     * @param year
     * @param month
     * @param dayOfMonth
     * @return
     */
    public static LocalDate handleSpecilDate(int year, int month, int dayOfMonth){
        return LocalDate.of(year, month, dayOfMonth);
    }

    /**
     * 比较两个日期是否相等
     * @param date
     * @param anotherDate
     * @return
     */
    public static boolean compareDate(LocalDate date, LocalDate anotherDate){
        return date.equals(anotherDate);
    }

    /**
     * 比较date 是否在anotherDate 之前
     * @param date
     * @param anotherDate
     * @return
     */
    public static boolean compareIsBefore(LocalDate date, LocalDate anotherDate){
        return date.isBefore(anotherDate);
    }

    /**
     * 比较date 是否在anotherDate 之后
     * @param date
     * @param anotherDate
     * @return
     */
    public static boolean compareIsAfter(LocalDate date, LocalDate anotherDate){
        return date.isAfter(anotherDate);
    }

    /**
     * 计算两个日期直接相差多少天
     * @param date
     * @param anotherDate
     * @return
     */
    public static int calcBetweenDays(LocalDate date, LocalDate anotherDate){
        Period periodToNextJavaRelease = Period.between(date, anotherDate);
        return periodToNextJavaRelease.getMonths();
    }

    /**
     * 计算两个日期直接相差几个月
     * @param date
     * @param anotherDate
     * @return
     */
    public static int calcBetweenMonths(LocalDate date, LocalDate anotherDate){
        Period periodToNextJavaRelease = Period.between(date, anotherDate);
        return periodToNextJavaRelease.getDays();
    }

    /**
     * 计算两个日期直接相差几年
     * @param date
     * @param anotherDate
     * @return
     */
    public static int calcBetweenYears(LocalDate date, LocalDate anotherDate){
        Period periodToNextJavaRelease = Period.between(date, anotherDate);
        return periodToNextJavaRelease.getYears();
    }

    /**
     * 处理周期性日期
     * 检查类似生日、纪念日、法定假日...
     * @param specialDate
     * @return
     */
    public static boolean cycleDate(LocalDate specialDate){
        MonthDay localDate = MonthDay.from(LocalDate.now());
        MonthDay specialDay = MonthDay.from(specialDate);
        return localDate.equals(specialDay);
    }

    /**
     * 获取下周的日期
     * @return
     */
    public static LocalDate neexWeek(){
        LocalDate localDate = LocalDate.now();
        return localDate.plus(1, ChronoUnit.WEEKS);
    }

    /**
     * 根据TemporalUnit,往后延迟n个Unit
     * @param amountToAdd
     * @param unit
     * @return
     */
    public static LocalDate plusDate(int amountToAdd, TemporalUnit unit){
        LocalDate localDate = LocalDate.now();
        return localDate.plus(amountToAdd, unit);
    }

    /**
     * 根据TemporalUnit,往前倒推n个Unit
     * @param amountToSubtract
     * @param unit
     * @return
     */
    public static LocalDate minusDate(int amountToSubtract, TemporalUnit unit){
        LocalDate localDate = LocalDate.now();
        return localDate.minus(amountToSubtract, unit);
    }

    /**
     * 判断今年是否为闰年
     * @return
     */
    public static boolean isLeapYear(){
        LocalDate today = LocalDate.now();
        return today.isLeapYear();
    }

    /**
     * 获取当前得时间戳
     * @return
     */
    public static String getTimestamp(){
        Instant timestamp = Instant.now();
        return timestamp.toString();
    }

    /**
     * 根据DateTimeFormatter格式化日期
     * @param text
     * @param formatter
     */
    public static LocalDate formateDate(CharSequence text, DateTimeFormatter formatter){
        LocalDate formatted = LocalDate.parse(text, formatter);
        return formatted;
    }

//    // 根据系统时间返回当前时间并设置为UTC。
//    Clock clock = Clock.systemUTC();
//
//    // 根据系统时钟区域返回时间
//    Clock defaultClock = Clock.systemDefaultZone();
}

 备注

  MyBatis从3.4.5版本开始就完全支持这种类型了,可以直接将属性对象设置为LocalDateTime;

public class User {
    private LocalDateTime createTime;
    // setter ... getter ... 省略了哈
}

public interface UserDao {
    @Insert("INSERT INTO user(create_time) values(#{createTime})")
    int insertUser(User user);
}

// 在set时间时,一般直接用now方法就好
user.setCreateTime(LocalDateTime.now());

// 如果发现时区问题可以直接在代码中指定,也可以修改mysql的my.ini的配置文件,在[mysqld]新增default-time-zone = '+08:00'
user.setCreateTime(LocalDateTime.now(ZoneId.of("+08:00")));

 

posted on 2020-05-29 23:49  愚蠢的猴子  阅读(394)  评论(0)    收藏  举报