java8日期时间LocalDate,LocalTime,LocalDateTime精讲

简介

伴随 lambda表达式、streams 以及一系列小优化,Java 8 推出了全新的日期时间API。

Java处理日期、日历和时间的不足之处:将 java.util.Date 设定为可变类型,以及 SimpleDateFormat 的非线程安全使其应用非常受限。然后就在 java8 上面增加新的特性。

全新API的众多好处之一就是,明确了日期时间概念,例如:瞬时(instant)、 长短(duration)、日期、时间、时区和周期。

同时继承了Joda 库按人类语言和计算机各自解析的时间处理方式。不同于老版本,新API基于ISO标准日历系统,java.time包下的所有类都是不可变类型而且线程安全。

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

package com.wq.study.java8.date;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.MonthDay;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.Period;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class DateTest {
    
    
    
    //获取今天的日期
    public void getCurrentDate(){
    
    
        LocalDate today = LocalDate.now();
        System.out.println("Today's Local date : " + today);
        
        //这个是作为对比
        Date date = new Date();
        System.out.println(date);
    }
    
    //获取年、月、日信息
    public void getDetailDate(){
    
    
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        
        System.out.printf("Year : %d  Month : %d  day : %d t %n", year, month, day);
    }
    
    //处理特定日期
    public void handleSpecilDate(){
    
    
        LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);
        System.out.println("The specil date is : " + dateOfBirth);
    }
    
    //判断两个日期是否相等
    public void compareDate(){
    
    
        LocalDate today = LocalDate.now();
        LocalDate date1 = LocalDate.of(2018, 01, 21);
        
        if(date1.equals(today)){
    
    
            System.out.printf("TODAY %s and DATE1 %s are same date %n", today, date1);
        }
    }
    
    //处理周期性的日期
    public void cycleDate(){
    
    
        LocalDate today = LocalDate.now();
        LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);
        
        MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(today);

        if(currentMonthDay.equals(birthday)){
    
    
           System.out.println("Many Many happy returns of the day !!");
        }else{
    
    
           System.out.println("Sorry, today is not your birthday");
        }
    }
    
    //获取当前时间
    public void getCurrentTime(){
    
    
        LocalTime time = LocalTime.now();
        System.out.println("local time now : " + time);
    }
    
    //增加小时
    public void plusHours(){
    
    
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(2); // 增加两小时
        System.out.println("Time after 2 hours : " +  newTime);
    }
    
    //如何计算一周后的日期
    public void nextWeek(){
    
    
        LocalDate today = LocalDate.now();
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("Today is : " + today);
        System.out.println("Date after 1 week : " + nextWeek);
    }
    
    //计算一年前或一年后的日期
    public void minusDate(){
    
    
        LocalDate today = LocalDate.now();
        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("Date before 1 year : " + previousYear);

        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("Date after 1 year : " + nextYear);
    }
    
    public void clock(){
    
    
        // 根据系统时间返回当前时间并设置为UTC。
        Clock clock = Clock.systemUTC();
        System.out.println("Clock : " + clock);

        // 根据系统时钟区域返回时间
        Clock defaultClock = Clock.systemDefaultZone();
        System.out.println("Clock : " + clock);
    }
    
    //如何用Java判断日期是早于还是晚于另一个日期
    public void isBeforeOrIsAfter(){
    
    
        LocalDate today = LocalDate.now(); 
        
        LocalDate tomorrow = LocalDate.of(2018, 1, 29);
        if(tomorrow.isAfter(today)){
    
    
            System.out.println("Tomorrow comes after today");
        }

        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);

        if(yesterday.isBefore(today)){
    
    
            System.out.println("Yesterday is day before today");
        }
    }
    
    //时区处理
    public void getZoneTime(){
    
    
        //设置时区
        ZoneId america = ZoneId.of("America/New_York");
        
        LocalDateTime localtDateAndTime = LocalDateTime.now();
        
        ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
        System.out.println("现在的日期和时间在特定的时区 : " + dateAndTimeInNewYork);
    }
    
    //使用 YearMonth类处理特定的日期
    public void checkCardExpiry(){
    
    
        YearMonth currentYearMonth = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
        
        YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY);
        System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
    }
    
    //检查闰年
    public void isLeapYear(){
    
    
        LocalDate today = LocalDate.now();
        if(today.isLeapYear()){
    
    
           System.out.println("This year is Leap year");
        }else {
    
    
            System.out.println("2018 is not a Leap year");
        }
    }
    
    //计算两个日期之间的天数和月数
    public void calcDateDays(){
    
    
        LocalDate today = LocalDate.now();
        
        LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14);
        
        Period periodToNextJavaRelease = Period.between(today, java8Release);
        
        System.out.println("Months left between today and Java 8 release : "
                                           + periodToNextJavaRelease.getMonths() );
    }
    
    // 包含时差信息的日期和时间
    public void ZoneOffset(){
    
    
        LocalDateTime datetime = LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30);
        ZoneOffset offset = ZoneOffset.of("+05:30");
        OffsetDateTime date = OffsetDateTime.of(datetime, offset);  
        System.out.println("Date and Time with timezone offset in Java : " + date);
    }
    
    // 获取时间戳
    public void getTimestamp(){
    
    
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant " + timestamp);
    }

    // 使用预定义的格式化工具去解析或格式化日期
    public void formateDate(){
    
    
        String dayAfterTommorrow = "20180210";
        LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted);
    }
    
    public static void main(String[] args) {
    
    
        DateTest dt = new DateTest();
        
        dt.formateDate();
    }

}

猜你喜欢

转载自blog.csdn.net/qq_37131111/article/details/120289500