Java8操作日期

一、Date与LocalDate互转

  • Date转LocalDate
 public static void main(String[] args) {
        Date date = new Date();
        LocalDate localDate = LocalDate.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("date2LocalDate:"+date2LocalDate(date));
    }
 
    /**
     * Date转LocalDate
     * @param date
     */
    public static LocalDate date2LocalDate(Date date) {
        if(null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }
  • LocalDate转Date
public static void main(String[] args) {
        Date date = new Date();
        LocalDate localDate = LocalDate.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("localDate2Date:"+localDate2Date(localDate));
    }
    /**
     * LocalDate转Date
     * @param localDate
     * @return
     */
    public static Date localDate2Date(LocalDate localDate) {
        if(null == localDate) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }
  • String转LocalDateTime
 DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime = LocalDateTime.parse(params.getLeaseEndTime()+" 00:00:00",df);
            LocalDateTime endTime = LocalDateTime.parse(params.getLeaseEndTime()+" 23:59:59",df);
            ZoneId zoneId = ZoneId.systemDefault();
            criteria.andModifyTimeBetween(Date.from(startTime.atZone(zoneId).toInstant()),Date.from(endTime.atZone(zoneId).toInstant()));

 

二、日期初识

  示例1: 获取当天日期

    Java 8中的 LocalDate 用于表示当天日期。和java.util.Date不同,它只有日期,不包含时间。

public static void main(String[] args) {
  LocalDate date = LocalDate.now();
  System.out.println("当前日期=" + date);
}

  示例2: 构造指定日期

    调用工厂方法LocalDate.of()创建任意日期, 该方法需要传入年、月、日做参数,返回对应的LocalDate实例。这个方法的好处是没再犯老API的设计错误,比如年度起始于1900,月份是从0开 始等等

public static void main(String[] args) {
    LocalDate date = LocalDate.of(2000, 1, 1);
    System.out.println("千禧年=" + date);
}

  示例3: 获取年月日信息

public static void main(String[] args) {
    LocalDate date = LocalDate.now();
    System.out.printf("年=%d, 月=%d, 日=%d", date.getYear(), date.getMonthValue(), date.getDayOfMonth());
}

  示例4: 比较两个日期是否相等

public static void main(String[] args) {
    LocalDate now = LocalDate.now();
    LocalDate date = LocalDate.of(2018, 9, 24);
    System.out.println("日期是否相等=" + now.equals(date));
}

    示例5:计算日期相差多少

LocalDate localDate1 = LocalDate.of(2017, 9, 1);
LocalDate localDate2 = LocalDate.of(2017, 10, 2);
Period next = Period.between(localDate1, localDate2);
System.out.println((int) (localDate2.toEpochDay() - localDate1.toEpochDay()));

三、时间初识

  示例: 获取当前时间

    Java 8中的 LocalTime 用于表示当天时间。和java.util.Date不同,它只有时间,不包含日期。

public static void main(String[] args) {
    LocalTime time = LocalTime.now();
    System.out.println("当前时间=" + time);
}

    计算时间相差多少

LocalDateTime now = LocalDateTime.now();
System.out.println("计算两个时间的差:");
LocalDateTime end = LocalDateTime.now();
Duration duration = Duration.between(now,end);
long days = duration.toDays(); //相差的天数
long hours = duration.toHours();//相差的小时数
long minutes = duration.toMinutes();//相差的分钟数
long millis = duration.toMillis();//相差毫秒数
long nanos = duration.toNanos();//相差的纳秒数
System.out.println(now);
System.out.println(end);

四、比较与计算

  示例1: 日期时间计算

    Java8提供了新的plusXxx()方法用于计算日期时间增量值,替代了原来的add()方法。新的API将返回一个全新的日期时间示例,需要使用新的对象进行接收。

 public static void main(String[] args) {
        
     // 时间增量
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(2);
        System.out.println("newTime=" + newTime);
        
     // 日期增量
        LocalDate date = LocalDate.now();
        LocalDate newDate = date.plus(1, ChronoUnit.WEEKS);
        System.out.println("newDate=" + newDate);
        
    }

  示例2: 日期时间比较

    Java8提供了isAfter()、isBefore()用于判断当前日期时间和指定日期时间的比较

 public static void main(String[] args) {
        
        LocalDate now = LocalDate.now();
        
        LocalDate date1 = LocalDate.of(2000, 1, 1);
        if (now.isAfter(date1)) {
            System.out.println("千禧年已经过去了");
        }
        
        LocalDate date2 = LocalDate.of(2020, 1, 1);
        if (now.isBefore(date2)) {
            System.out.println("2020年还未到来");
        }
        
    }

五、时区

  示例: 创建带有时区的日期时间

    Java 8不仅分离了日期和时间,也把时区分离出来了。现在有一系列单独的类如ZoneId来处理特定时区,ZoneDateTime类来表示某时区下的时间。

 public static void main(String[] args) {
        
        // 上海时间
        ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
        ZonedDateTime shanghaiZonedDateTime = ZonedDateTime.now(shanghaiZoneId);
        
        // 东京时间
        ZoneId tokyoZoneId = ZoneId.of("Asia/Tokyo");
        ZonedDateTime tokyoZonedDateTime = ZonedDateTime.now(tokyoZoneId);
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("上海时间: " + shanghaiZonedDateTime.format(formatter));
        System.out.println("东京时间: " + tokyoZonedDateTime.format(formatter));
        
    }

六、格式化

  示例1: 使用预定义格式解析与格式化日期

public static void main(String[] args) {
        
        // 解析日期
        String dateText = "20180924";
        LocalDate date = LocalDate.parse(dateText, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println("格式化之后的日期=" + date);
        
        // 格式化日期
        dateText = date.format(DateTimeFormatter.ISO_DATE);
        System.out.println("dateText=" + dateText);
        
    }
 

  示例2: 日期和字符串的相互转换

 public static void main(String[] args) {
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        // 日期时间转字符串
        LocalDateTime now = LocalDateTime.now();
        String nowText = now.format(formatter);
        System.out.println("nowText=" + nowText);
        
        // 字符串转日期时间
        String datetimeText = "1999-12-31 23:59:59";
        LocalDateTime datetime = LocalDateTime.parse(datetimeText, formatter);
        System.out.println(datetime);
        
    }

七、相关类说明

Instant         时间戳
Duration        持续时间、时间差
LocalDate       只包含日期,比如:2018-09-24
LocalTime       只包含时间,比如:10:32:10
LocalDateTime   包含日期和时间,比如:2018-09-24 10:32:10
Peroid          时间段
ZoneOffset      时区偏移量,比如:+8:00
ZonedDateTime   带时区的日期时间
Clock           时钟,可用于获取当前时间戳
java.time.format.DateTimeFormatter      时间格式化类

八、前后端日期转换

@JSONField(format = "yyyy-MM-dd HH:mm:ss")
    
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

九、日期和date转换

String 转 Date

private Date getDateByString(String datetimeText) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime hopeArriveTime = LocalDateTime.parse(datetimeText, formatter);
    ZoneId zoneId = ZoneId.systemDefault();
    ZonedDateTime zdt = hopeArriveTime.atZone(zoneId);
    return Date.from(zdt.toInstant());
}

Date 转 String

Date leaseStartTime = gardenCompany.getLeaseStartTime();
Date leaseEndTime = gardenCompany.getLeaseEndTime();
LocalDate startTime = leaseStartTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate endTime = leaseEndTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
currentLease = startTime.format(formatter) + "-" + endTime.format(formatter);

十、两个日期相差时间

 public static void main(String[] args) {
        System.out.println(LocalDate.now().toEpochDay() - LocalDate.now().minusDays(5).toEpochDay());
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章